본문 바로가기

프로그래밍 언어/Java

[Java] 묵시적. 명시적 형 변환

묵시적 형 변환 (Implicit Type Conversion)


자바에서 묵시적 형 변환이란 자동으로 형 변환 해주는 경우를 의미한다. 





명시적 형 변환 (Explicit Type Conversion)


데이터 앞에 변환할 타입으로 명시해주는 경우를 의미한다. 

주로 큰 데이터 타입을 작은 데이터 타입으로 변환할 때 사용되며, 데이터 손실의 가능성이 있어 명시적으로 형 변환을 해주지 않을 경우 에러가 발생한다.




<그림>







<예시>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class CastingEx {
    public static void main(String[] args) {
        CastingEx ex = new CastingEx();
        ex.implicitTypeConversion();
        ex.explicitTypeConversion();
    }
    void implicitTypeConversion() {
        byte a = 65;
        short b = 66;
        char c = 67;
        int d = 68;
        long e = 69;
        float f = 70;
        double g = 71;
        
        g = f;
        f = e;
        e = d;
        d = c;
        d = b;
        b = a;
    }
    void explicitTypeConversion() {
        byte a = 65;
        short b = 66;
        char c = 67;
        int d = 68;
        long e = 69;
        float f = 70;
        double g = 71;
        
        a = (byte)b;
        a = (byte)c;
        b = (short)d;
        c = (char)d;
        d = (int)e;
        e = (long)f;
        f = (float)g;
    }
}
cs




<묵시적 형 변환>


 16

  float to double

 17

  long to float 

 18

  int to long 

 19 

  char to int

 20

  short to int

 21

  byte to short 

 

 


<명시적 형 변환>


 32

  (byte)short to byte

 33

  (byte)char to byte

 34 

  (short)int to short 

 35

  (char)int to char

 36

  (int)long to int

 37

  (long)float to long

 38

  (float)double to float