I about me

TypeCasting 본문

Java

TypeCasting

ssungni 2024. 2. 8. 14:51

파이썬에서는 'int( __ )' 이런 식으로 바꿔주는게 국룰인데, 

자바에서는 '(int) __ ' 이런 느낌인게 신기했다...

 

public class _07_TypeCasting {
    public static void main(String[] args) {
        // 형변환 TypeCasting
        // 정수형에서 실수형으로
        // 실수형에서 정수형으로

        // int to float, double
        int score = 93;
        System.out.println(score); // 93
        System.out.println((float)score); // 93.0
        System.out.println((double)score); // 93.0

        System.out.println(" ");

        // float, double to int
        float score_f = 93.3F;
        double score_d = 98.8;
        System.out.println((int)score_f); // 93
        System.out.println((int)score_d); // 98

        System.out.println(" ");

        // 정수 + 실수 연산
        score = 93 + (int) 98.5; // 93 + 98
        System.out.println(score); // 191

        score_d = (double) 93 + 98.3; // 93.0 + 98.8
        System.out.println(score_d); // 191.8

        System.out.println(" ");

        // 변수에 형 변환된 데이터 집어넣기
        double convertedScoreDouble = score; // 191 -> 191.0
        // 큰 범위로 갈 때는 자동 형변환
        // int -> long -> float -> double

        int convertedScoreInt = (int) score_d; // 191.8 -> 191
        // 작은 범위로 갈 때는 수동 형변환
        // double -> float -> long -> int

        System.out.println(" ");

        // 순자를 문자열로
        String s1 = String.valueOf(93);
        s1 = Integer.toString(93);
        System.out.println(s1);

        String s2 = String.valueOf(98.8);
        s2 = Double.toString(98.8);
        System.out.println(s2);

        System.out.println(" ");

        // 문자열을 순자로
        int i = Integer.parseInt("93");
        System.out.println(i);
        double d = Double.parseDouble("98.8");
        System.out.println(d);
    }
}

'Java' 카테고리의 다른 글

[MidTerm] 1. Java Elements  (0) 2024.04.22
[MidTerm] 0. Introduction to Java  (0) 2024.04.22
Constants  (0) 2024.02.08
VariableNaming  (0) 2024.02.08
Comment  (0) 2024.02.08