변수의 정의
변수는 변할수 있는 문자
자연수 = 1, 2, 3~~
정수(integer) = ~~ -3, -2, -1, 0, 1, 2, 3~~
1.1 은 real number 실수라고 한다 double형으로 쓰면 된다
문자열은 String
자바는 다른 언어들과 다르게 변수를 지정할 때 변수값의 데이터타입을 지정해야 한다
그 이유는 오류를 찾기 쉽고 구별이 되기 때문이다
public class Variable {
public static void main(String[] args) {
int a = 1; // Number -> integer
System.out.println(a);
double b = 1.1; // real number -> double
System.out.println(b);
String c = "Hello World";
System.out.println(c);
}
}
변수의 효용
public class Letter {
public static void main(String[] args) {
String name = "A";
System.out.println("Hello, " +name+" ... "+name+" ... "+name+" ... bye");
double VAT = 10.0;
System.out.println(VAT);
}
}
데이터 타입의 변환 (casting)
정수를 double형에 담으면 .0 이 붙는다
1.1을 강제로 정수로 바꾸면 소수점이 없어지므로 손실이 일어나서 1로 출력
숫자를 문자열로 바꾸려면
String f = Integer.toString(1); 이런식으로 하면 된다
데이터타입을 알려주는 것 .getClass()를 이용하면 String 형임을 알 수 있다
public class Casting {
public static void main(String[] args) {
double a = 1.1;
double b = 1;
double b2 = (double) 1;
System.out.println(b);
// int c = 1.1;
double d = 1.1;
int e = (int) 1.1;
System.out.println(e);
// 1 to String
String f = Integer.toString(1);
System.out.println(f.getClass());
}
}