본문 바로가기

언어/Java

[ 자바 / Java ] 비교 연산자 사용하기

반응형

자바의 비교 연산자(Comparison Operators)는 두 개의 값을 비교하고, 그 결과를 논리적으로 평가하는 데 사용됩니다. 비교 연산자의 결과는 항상 boolean 타입으로, true 또는 false를 반환합니다. 자바에서는 다음과 같은 비교 연산자를 제공합니다:

  1. 등호 연산자 (==)
  2. 부등호 연산자 (!=)
  3. 크다 (>)
  4. 작다 (<)
  5. 크거나 같다 (>=)
  6. 작거나 같다 (<=)

각 연산자의 사용법과 동작을 자세히 살펴보겠습니다.

1. 등호 연산자 (==)

등호 연산자는 두 값이 같은지 비교합니다. 값이 같으면 true, 다르면 false를 반환합니다.

예시:

public class EqualityOperatorExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 5;
        int c = 10;

        System.out.println(a == b); // true
        System.out.println(a == c); // false

        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");

        System.out.println(str1 == str2); // true (같은 문자열 리터럴을 가리킴)
        System.out.println(str1 == str3); // false (다른 객체를 가리킴)
    }
}

위의 예시에서 == 연산자는 정수와 문자열 리터럴을 비교하는 데 사용되었습니다. 두 문자열 리터럴이 같은 객체를 가리키기 때문에 str1 == str2true를 반환하지만, str3는 새로운 객체로 생성되었기 때문에 str1 == str3false를 반환합니다.

2. 부등호 연산자 (!=)

부등호 연산자는 두 값이 다른지 비교합니다. 값이 다르면 true, 같으면 false를 반환합니다.

예시:

public class InequalityOperatorExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;
        int c = 5;

        System.out.println(a != b); // true
        System.out.println(a != c); // false

        String str1 = "Hello";
        String str2 = "World";

        System.out.println(str1 != str2); // true (다른 문자열)
    }
}

위의 예시에서 != 연산자는 정수와 문자열을 비교하는 데 사용되었습니다. 값이 다르면 true를 반환합니다.

3. 크다 (>)

크다 연산자는 왼쪽 값이 오른쪽 값보다 큰지 비교합니다. 왼쪽 값이 크면 true, 그렇지 않으면 false를 반환합니다.

예시:

public class GreaterThanOperatorExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        System.out.println(a > b); // true
        System.out.println(b > a); // false
    }
}

위의 예시에서 > 연산자는 두 정수를 비교하여, ab보다 큰지 확인합니다.

4. 작다 (<)

작다 연산자는 왼쪽 값이 오른쪽 값보다 작은지 비교합니다. 왼쪽 값이 작으면 true, 그렇지 않으면 false를 반환합니다.

예시:

public class LessThanOperatorExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println(a < b); // true
        System.out.println(b < a); // false
    }
}

위의 예시에서 < 연산자는 두 정수를 비교하여, ab보다 작은지 확인합니다.

5. 크거나 같다 (>=)

크거나 같다 연산자는 왼쪽 값이 오른쪽 값보다 크거나 같은지 비교합니다. 왼쪽 값이 크거나 같으면 true, 그렇지 않으면 false를 반환합니다.

예시:

public class GreaterThanOrEqualOperatorExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 10;
        int c = 5;

        System.out.println(a >= b); // true
        System.out.println(a >= c); // true
        System.out.println(c >= a); // false
    }
}

위의 예시에서 >= 연산자는 두 정수를 비교하여, ab보다 크거나 같은지 확인합니다.

6. 작거나 같다 (<=)

작거나 같다 연산자는 왼쪽 값이 오른쪽 값보다 작거나 같은지 비교합니다. 왼쪽 값이 작거나 같으면 true, 그렇지 않으면 false를 반환합니다.

예시:

public class LessThanOrEqualOperatorExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println(a <= b); // true
        System.out.println(b <= a); // false
        System.out.println(a <= 5); // true
    }
}

위의 예시에서 <= 연산자는 두 정수를 비교하여, ab보다 작거나 같은지 확인합니다.

7. 객체 비교와 equals 메서드

객체 비교에서는 == 연산자와 equals 메서드의 차이를 이해하는 것이 중요합니다.

  • == 연산자는 두 객체 참조가 같은 객체를 가리키는지 확인합니다.
  • equals 메서드는 두 객체의 값이 같은지 확인합니다. 이 메서드는 Object 클래스에서 제공되며, 필요에 따라 재정의할 수 있습니다.

예시:

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

        System.out.println(str1 == str2); // false (다른 객체를 가리킴)
        System.out.println(str1.equals(str2)); // true (값이 같음)

        Integer num1 = new Integer(100);
        Integer num2 = new Integer(100);

        System.out.println(num1 == num2); // false (다른 객체를 가리킴)
        System.out.println(num1.equals(num2)); // true (값이 같음)
    }
}

위의 예시에서 == 연산자는 두 객체가 동일한 메모리 주소를 가리키는지 확인하지만, equals 메서드는 두 객체의 값이 같은지를 확인합니다.

8. 비교 연산자의 사용 예

다양한 상황에서 비교 연산자를 사용하는 예제를 보겠습니다:

public class ComparisonOperatorsDemo {
    public static void main(String[] args) {
        int x = 10;
        int y = 20;

        // 숫자 비교
        System.out.println("x == y: " + (x == y)); // false
        System.out.println("x != y: " + (x != y)); // true
        System.out.println("x > y: " + (x > y)); // false
        System.out.println("x < y: " + (x < y)); // true
        System.out.println("x >= y: " + (x >= y)); // false
        System.out.println("x <= y: " + (x <= y)); // true

        // 문자열 비교
        String str1 = "Apple";
        String str2 = "Banana";
        String str3 = "Apple";

        System.out.println("str1 == str2: " + (str1 == str2)); // false
        System.out.println("str1 == str3: " + (str1 == str3)); // true
        System.out.println("str1.equals(str3): " + str1.equals(str3)); // true

        // 참조 타입 비교
        StringBuilder sb1 = new StringBuilder("Hello");
        StringBuilder sb2 = new StringBuilder("Hello");

        System.out.println("sb1 == sb2: " + (sb1 == sb2)); // false (다른 객체를 가리킴)
        System.out.println("sb1.equals(sb2)); // false (StringBuilder는 equals를 재정의하지 않음)

        // Float 비교
        float a = 0.1f;
        float b = 0.2f;
        float c = 0.3f;

        System.out.println("a + b == c: " + ((a + b) == c)); // false (부동 소수점 정확도 문제)
        System.out.println("Math.abs(a + b - c) < 0.00001: " + (Math.abs(a + b - c) < 0.00001)); // true (허용 오차 내에서 비교)
    }
}

이 예제에서는 숫자, 문자열, 참조 타입, 부동 소수점 숫자 등을 비교하는 다양한 비교 연산자의 사용을 보여줍니다.

9. 요약

자바의 비교

연산자는 두 값 또는 객체를 비교하여 true 또는 false를 반환하는 데 사용됩니다. 숫자, 문자열, 객체 등 다양한 데이터 타입에 대해 비교 연산자를 사용하여 조건을 평가할 수 있습니다. 각 연산자의 동작 방식을 이해하고, 객체 비교에서 ==equals의 차이를 명확히 이해하는 것이 중요합니다.

반응형