Java

[Effective Java] ์•„์ดํ…œ 60. ์ •ํ™•ํ•œ ๋‹ต์ด ํ•„์š”ํ•˜๋‹ค๋ฉด float์™€ double์€ ํ”ผํ•˜๋ผ, ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…๋ณด๋‹ค๋Š” ๊ธฐ๋ณธ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋ผ.

quedevel 2023. 3. 27. 14:30
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽฏ ์•„์ดํ…œ 60. ์ •ํ™•ํ•œ ๋‹ต์ด ํ•„์š”ํ•˜๋‹ค๋ฉด float์™€ double์€ ํ”ผํ•˜๋ผ.

float์™€ double ํƒ€์ž…์€ ๊ณผํ•™๊ณผ ๊ณตํ•™ ๊ณ„์‚ฐ์šฉ์œผ๋กœ ์„ค๊ณ„๋˜์—ˆ๋‹ค. ์ด์ง„ ๋ถ€๋™์†Œ์ˆ˜์  ์—ฐ์‚ฐ์— ์“ฐ์ด๋ฉฐ,๋„“์€ ๋ฒ”์œ„์˜ ์ˆ˜๋ฅผ ๋น ๋ฅด๊ฒŒ ์ •๋ฐ€ํ•œ '๊ทผ์‚ฌ์น˜'๋กœ ๊ณ„์‚ฐํ•˜๋„๋ก ์„ธ์‹ฌํ•˜๊ฒŒ ์„ค๊ณ„๋˜์—ˆ๋‹ค. ๋”ฐ๋ผ์„œ, ์ •ํ™•ํ•œ ๊ฒฐ๊ณผ๊ฐ€ ํ•„์š”ํ•  ๋•Œ๋Š” ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ ๋œ๋‹ค. float์™€ double ํƒ€์ž…์€ ํŠนํžˆ ๊ธˆ์œต ๊ด€๋ จ ๊ณ„์‚ฐ๊ณผ๋Š” ๋งž์ง€ ์•Š๋Š”๋‹ค.

๋”ฐ๋ผ์„œ, ๊ธˆ์œต ๊ณ„์‚ฐ์—๋Š” BigDecimal, int ํ˜น์€ long์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

๐ŸŽฏ ์•„์ดํ…œ 61. ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…๋ณด๋‹ค๋Š” ๊ธฐ๋ณธ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋ผ.

๊ธฐ๋ณธ ํƒ€์ž… vs ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…

1๏ธโƒฃ ๊ธฐ๋ณธ ํƒ€์ž…์€ ๊ฐ’๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋‚˜, ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…์€ ๊ฐ’์— ๋”ํ•ด ์‹๋ณ„์„ฑ์ด๋ž€ ์†์„ฑ์„ ๊ฐ–๋Š”๋‹ค.

public class Main {
    public static void main(String[] args) {
        int a = 1;
        int b = 1;
        System.out.println("(b == a) : " + (b == a)); // (b == a) : true
        Integer boxedIntegerA = new Integer(1);
        Integer boxedIntegerB = new Integer(1);
        System.out.println("(boxedIntegerB == boxedIntegerA) : " + (boxedIntegerB == boxedIntegerA)); // (boxedIntegerB == boxedIntegerA) : false
        System.out.println("boxedIntegerB.equals(boxedIntegerA) : " + boxedIntegerB.equals(boxedIntegerA)); // boxedIntegerB.equals(boxedIntegerA) : true
    }
}

2๏ธโƒฃ ๊ธฐ๋ณธ ํƒ€์ž…์˜ ๊ฐ’์€ ์–ธ์ œ๋‚˜ ์œ ํšจํ•˜๋‚˜, ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…์€ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’, ์ฆ‰ null์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

public class Main {
    static int a;
    static Integer i;
    public static void main(String[] args) {
        if (a < 1) System.out.println(a);
        if (i < 1) System.out.println(i);
    }
}


3๏ธโƒฃ ๊ธฐ๋ณธ ํƒ€์ž…์ด ๋ฐ•์‹ฑ๋œ ๊ธฐ๋ณธ ํƒ€์ž…๋ณด๋‹ค ์‹œ๊ฐ„๊ณผ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฉด์—์„œ ๋” ํšจ์œจ์ ์ด๋‹ค.


์ฐธ๊ณ  ์ž๋ฃŒ

Joshua Bloch, ใ€ŽEffective Java 3/Eใ€, ๊ฐœ์•ž๋งต์‹œ ์˜ฎ๊น€, ํ”„๋กœ๊ทธ๋ž˜๋ฐ์ธ์‚ฌ์ดํŠธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=

728x90
๋ฐ˜์‘ํ˜•