김코딩

자바 - 형변환 본문

Java

자바 - 형변환

김코딩딩 2024. 4. 25. 18:34

형변환

int -> long -> double

- 작은 범위에서 큰 범위로는 대입할 수 있다.

  -> 이것을 묵시적 형변환 또는 자동 형변환이라 한다.

- 큰 범위에서 작은 범위의 대입은 다음과 같은 문제가 발생할 수 있다. 이때는 명시적 형변환을 사용해야 한다.

  -> 소수점 버림

  -> 오버플로우

- 연산과 형변환

  -> 같은 타입은 같은 결과를 낸다.

  -> 서로 다른 타입의 계산은 큰 범위로 자동 형변환이 일어난다.

 

예제 1

package castiong;

public class casting1 {
    public static void main(String[] args) {
        int intValue = 10;
        long longValue;
        double doubleValue;

        longValue = intValue;
        System.out.println("longValue = " + longValue);
        
        doubleValue = intValue;
        System.out.println("doubleValue = " + doubleValue);

        doubleValue = 20L;
        System.out.println("doubleValue2 = " + doubleValue);
    }
}

 

예제 2

package castiong;

public class casting2 {
    public static void main(String[] args) {
        double doubleValue = 1.5;
        int intValue = 0;

//        intValue = doubleValue
        intValue = (int) doubleValue;
        System.out.println(intValue);

        int z = (int) 10.5;

        System.out.println(z);
    }
}

 

예제 3

package castiong;

public class casting3 {
    public static void main(String[] args) {
        long maxIntvalue = 2147483647; //int 최고값
        long maxIntOver = 2147483650L; //int 최고값 + 1(초과)
        int intValue = 0;

        intValue = (int) maxIntvalue;
        System.out.println("maxIntValue casting = " + intValue);

        intValue = (int) maxIntOver;
        System.out.println("maxIntOver casting = " + intValue);
    }
}

 

예제 4

package castiong;

public class casting4 {
    public static void main(String[] args) {
        int div1 = 3/2; //1
        System.out.println("divi = " + div1);

        double div2 = 3/2; //1.0
        System.out.println("div2 = " + div2);

        double div3 = 3.0/2; //1.5
        System.out.println("div3 = " + div3);

        double div4 = (double) 3/2; //1.5
        System.out.println("div4 = " + div4);

        int a= 3;
        int b = 2;
        double result = (double) a/b;
        System.out.println("result = " + result); //1.5
    }
}

'Java' 카테고리의 다른 글

자바 - 다형성1  (0) 2025.04.01
자바 - 메서드  (0) 2025.02.26
자바 - 반복문  (0) 2025.01.31
자바 - Scanner  (1) 2024.04.25