Problem Description | Incompatible types. Found: 'int', required: 'boolean'
해석 : 발견된 int 타입과 요구되는 boolean 타입은 상호호환되지 않는다.
public class VarEx3 {
public static void main(String[] args) {
final int score = 100;
// score = 200;
boolean power = 0;
System.out.println(score);
}
}
Problem Description | java : incompatible types: possible lossy conversion from int to byte
해석 : int형을 byte형으로 형변환 시 lossy할 수 있기 때문에 자바는 허용하지 않는다.
package ch02;
public class VarEx3 {
public static void main(String[] args) {
final int score = 100;
// score = 200;
byte b = 128; // 에러. -128~127
int oct = 010; // 8진수, 10진수로 8
int hex = 0x10; // 16진수, 10진수로 16
// System.out.println(score);
long l = 10_000_000_000L;
float f = 3.14; // 에러. 접미사 f를 생략하면 컴파일러는 d로 해석한다.
double d =3.14;
System.out.println(oct);
System.out.println(hex);
System.out.println(10.);
System.out.println(.10);
System.out.println(10f);
System.out.println(1e3);
}
}
변수와 마찬가지로 ‘값을 저장할 수 있는 공간'이지만, 변수와 달리 한 번 값을 저장하면 다른 값으로 변경할 수 없다.
final int MAX_SPEED = 10;
리터럴
그 자체로 값을 의미하는 것
상수가 필요한 이유
final WIDTH = 20; // 폭
final int HEIGHT = 10; // 높이
int triangleArea = (WIDTH * HEIGHT) / 2; // 삼각형의 면적을 구하는 공식
int rectangleArea = (WIDTH * HEIGHT); // 사각형의 면적을 구하는 공식
상수를 이용해서 기존의 코드를 변경한 것인데, 이전 코드에 비해 면적을 구하는 공식의 의미가 명확해졌다. 그리고 다른 값으로 계산할 때도 여러 곳을 수정할 필요없이 상수의 초기화만 다른 값으로 해주면 된다. 이처럼 상수는 리터럴에 있는 ‘의미있는 이름'을 붙여서 코드의 이해와 수정을 쉽게 만든다.