JAVA

Java 값 비교 시 주의점

지오준 2024. 5. 31.
반응형

Java에서 값을 비교할 때는 몇 가지 주의해야 할 점이 있습니다. 이 글에서는 그 주의점들을 살펴보고, 샘플 코드를 통해 어떻게 올바르게 값을 비교할 수 있는지 알아보겠습니다.

1. 기본 타입(Primitive Type) 비교

기본 타입(primitive type)에는 int, char, float, double, boolean 등이 있습니다. 이 타입들은 == 연산자를 사용해 비교할 수 있습니다. 기본 타입의 경우, == 연산자는 두 값이 같은지를 비교합니다.

public class PrimitiveComparison {
    public static void main(String[] args) {
        int a = 5;
        int b = 5;
        if (a == b) {
            System.out.println("a와 b는 같습니다.");
        } else {
            System.out.println("a와 b는 다릅니다.");
        }
    }
}

2. 객체 타입(Object Type) 비교

객체 타입의 경우 == 연산자는 두 객체의 메모리 주소를 비교합니다. 따라서, 두 객체가 같은 값을 가지더라도 == 연산자는 false를 반환할 수 있습니다. 객체의 값을 비교하려면 equals() 메서드를 사용해야 합니다.

public class ObjectComparison {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = new String("Hello");

        // 주소 비교
        if (str1 == str2) {
            System.out.println("str1과 str2는 같은 객체를 참조합니다.");
        } else {
            System.out.println("str1과 str2는 다른 객체를 참조합니다.");
        }

        // 값 비교
        if (str1.equals(str2)) {
            System.out.println("str1과 str2는 같은 값을 가집니다.");
        } else {
            System.out.println("str1과 str2는 다른 값을 가집니다.");
        }
    }
}

3. 오토박싱(Autoboxing)과 언박싱(Unboxing) 주의

Java는 기본 타입을 객체 타입으로 자동 변환해주는 오토박싱(Autoboxing)과 객체 타입을 기본 타입으로 변환해주는 언박싱(Unboxing)을 지원합니다. 이 과정에서 == 연산자를 사용할 때 예상치 못한 결과가 나올 수 있습니다.

public class AutoboxingComparison {
    public static void main(String[] args) {
        Integer a = 128;
        Integer b = 128;

        if (a == b) {
            System.out.println("a와 b는 같은 객체를 참조합니다.");
        } else {
            System.out.println("a와 b는 다른 객체를 참조합니다.");
        }

        if (a.equals(b)) {
            System.out.println("a와 b는 같은 값을 가집니다.");
        } else {
            System.out.println("a와 b는 다른 값을 가집니다.");
        }
    }
}

위 코드에서 a와 b는 Integer 객체이므로 == 연산자는 주소를 비교하고, equals() 메서드는 값을 비교합니다. 128 이상의 값에서는 새로운 객체가 생성되기 때문에 == 연산자는 false를 반환합니다.

4. Null 체크

객체를 비교할 때는 NullPointerException을 방지하기 위해 null 체크가 필요합니다.

public class NullComparison {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "Hello";

        // null 체크 후 비교
        if (str1 != null && str1.equals(str2)) {
            System.out.println("str1과 str2는 같은 값을 가집니다.");
        } else {
            System.out.println("str1과 str2는 다른 값을 가집니다.");
        }
    }
}

결론

Java에서 값을 비교할 때는 기본 타입과 객체 타입을 구분하고, == 연산자와 equals() 메서드의 차이를 이해하는 것이 중요합니다. 오토박싱과 언박싱에 주의하고, null 체크를 통해 예외 상황을 방지해야 합니다. 이러한 주의점을 잘 지켜야 올바른 값을 비교할 수 있습니다.

반응형

댓글