Double 과 Integer 구분하기
이 단계에서는 Java 에서 double과 int (정수) 값의 차이점을 살펴보고, 특히 유사하게 보이는 숫자를 다룰 때 어떻게 구분하는지 알아보겠습니다. double은 소수점이 있는 숫자와 정수를 모두 나타낼 수 있지만, int는 정수만 나타낼 수 있습니다. 이 차이점을 이해하는 것은 올바른 데이터 타입을 선택하고 정확한 계산을 수행하는 데 매우 중요합니다.
WebIDE 의 파일 탐색기를 사용하여 ~/project 디렉토리에 NumberTypes.java라는 새 Java 파일을 생성해 보겠습니다.
NumberTypes.java를 열고 다음 코드를 추가합니다.
public class NumberTypes {
public static void main(String[] args) {
// An integer variable
int integerValue = 10;
// A double variable representing a whole number
double doubleValueWhole = 20.0;
// A double variable representing a number with a decimal part
double doubleValueDecimal = 30.5;
// Print the values and their types (implicitly)
System.out.println("Integer value: " + integerValue);
System.out.println("Double value (whole): " + doubleValueWhole);
System.out.println("Double value (decimal): " + doubleValueDecimal);
// Check the type using instanceof (for wrapper classes)
Integer integerObject = 100;
Double doubleObject = 200.0;
System.out.println("Is integerObject an instance of Integer? " + (integerObject instanceof Integer));
System.out.println("Is doubleObject an instance of Double? " + (doubleObject instanceof Double));
System.out.println("Is integerObject an instance of Double? " + (integerObject instanceof Double));
System.out.println("Is doubleObject an instance of Integer? " + (doubleObject instanceof Integer));
// Demonstrate potential issues with comparing double and int
System.out.println("Is integerValue equal to doubleValueWhole? " + (integerValue == doubleValueWhole)); // This comparison works due to type promotion
// System.out.println("Is integerValue equal to doubleValueDecimal? " + (integerValue == doubleValueDecimal)); // This would be false
}
}
이 코드에서:
int 변수 integerValue를 선언합니다.
- 두 개의
double 변수를 선언하는데, 하나는 정수 (doubleValueWhole) 를 나타내고 다른 하나는 소수 부분이 있는 숫자 (doubleValueDecimal) 를 나타냅니다.
- 이러한 값을 출력하여 표현을 관찰합니다.
- 첫 번째 단계에서 했던 것과 유사하게, 래퍼 클래스
Integer 및 Double과 함께 instanceof 연산자를 사용하여 객체 유형을 명시적으로 확인합니다.
- 또한
int와 double 간의 비교를 보여줍니다. Java 는 타입 프로모션을 수행하여 비교 전에 int를 double로 변환하므로 integerValue == doubleValueWhole은 true로 평가됩니다.
NumberTypes.java 파일을 저장합니다.
이제 프로그램을 컴파일하고 실행해 보겠습니다. 터미널을 열고 ~/project 디렉토리에 있는지 확인합니다.
코드를 컴파일합니다.
javac NumberTypes.java
컴파일된 코드를 실행합니다.
java NumberTypes
다음과 유사한 출력을 볼 수 있습니다.
Integer value: 10
Double value (whole): 20.0
Double value (decimal): 30.5
Is integerObject an instance of Integer? true
Is doubleObject an instance of Double? true
Is integerObject an instance of Double? false
Is doubleObject an instance of Integer? false
Is integerValue equal to doubleValueWhole? true
이 출력은 int와 double 값이 저장되고 표현되는 방식의 차이점과 래퍼 클래스와 함께 instanceof를 사용하여 해당 유형을 확인하는 방법을 보여줍니다. double은 정수 값을 가질 수 있지만, 근본적으로 정수 유형과는 구별되는 부동 소수점 유형입니다.