class castClass
{
public static void main(String[] args)
{
/*
자료형의 변환
boolean 2 byte
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte 우선순위
char 2 byte
우선순위 높고 낮음
자동 형 변환( small - > big 가능 )
강제 형 변환( big -> small이 안되기 때문에 강제로 형 변환 해주는 것 ) == cast 변환
우선순위 크 기
double 8
float 4
long 8
int 8
short char 2
byte 1
*/
short sh = 10;
int i;
i = sh;//자동 형 변환
System.out.println("i = " + i);
//아래 코드는 오류 i가 int형으로 short형인 sh보다 크기 때문에
//sh = i;
//따라서 cast 연산해줘서 강제 형 변환을 해줘야함
sh = (short)i;
System.out.println("sh = " + sh);
long l = 1231231231231231L;
float f = l;
System.out.println("f = " + f);
/*
ex)
1.23423425E13
1.23423425 * 10의 13승
*/
double d = l;
System.out.println("d = " + d);
double d1 = 1.23e2;// 원래 값은 1.23에 10의 2승을 한 값이라는 의미 (지수표기법)
System.out.println("d1 = " + d1);
double d2 = 1.23e-2;// 원래 값은 1.23에 10의 -2승을 한 값이라는 의미 (지수표기법)
System.out.println("d2 = " + d2);
double d3;
d3 = (double)3 / 2;//연산은 우선순위가 높은 자료형을 따라간다.
System.out.println("d3 = " + d3);
int j;
double val = 123.4567;
j = (int)val;//실수형을 정수형으로 강제 형 변환 하면 소숫점 이하는 다 사라진다.
System.out.println("j = " + j);
char ch = 'A';
int charNum = ch;
System.out.println("charNum = " + charNum);
}
}
Cast 우선 순위
1. 실수형 > 정수형
2. 자료형 크기 순
연산할 때 우선순위가 가장 높은 자료 형으로 연산이 된다.
실수형을 정수형으로 cast 변환 하면 소숫점 이하는 다 사라진다.
'IT Study > Java' 카테고리의 다른 글
Switch case 문 연습 (0) | 2018.05.03 |
---|---|
if문 연습 (0) | 2018.05.03 |
랜덤 함수 이용 및 응용 (0) | 2018.05.02 |
기본 실습(삼항연산자 응용) (0) | 2018.05.02 |
연산자 종합 실습(간단한 거스름돈 계산 문제) (0) | 2018.05.02 |