비교 연산자: 동등성, 관계, 논리적 비교
Java는 두 값이나 객체를 비교하는 데 사용되는 여러 가지 동등성 및 관계 연산자를 제공합니다. 이러한 연산자들은 주로 조건문이나 제어 흐름 문맥에서 사용됩니다.
동등성 연산자 (Equality Operators)
==
(동등 연산자)!=
(부동등 연산자)
관계 연산자 (Relational Operators)
<
(작음 연산자)>
(큼 연산자)<=
(작거나 같음 연산자)>=
(크거나 같음 연산자)
사용 예시:
Integer comparison:
10 == 20: false
10 != 20: true
10 > 20: false
10 < 20: true
10 >= 20: false
10 <= 20: true
Double comparison:
3.14 == 2.71: false
3.14 != 2.71: true
3.14 > 2.71: true
3.14 < 2.71: false
3.14 >= 2.71: true
3.14 <= 2.71: false
String comparison:
Apple.equals(Banana): false
Apple.compareTo(Banana): -1
Apple.equalsIgnoreCase(Banana): false
Object comparison:
Person{name='Alice', age=30} == Person{name='Bob', age=35}: false
Person{name='Alice', age=30}.equals(Person{name='Bob', age=35}): false
Logical comparison:
true && false: false
true || false: true
!(true): false
Grade calculation:
Grade: B
이 프로그램의 실행 결과는 다음과 같습니다:
Integer comparison:
10 == 20: false
10 != 20: true
10 > 20: false
10 < 20: true
10 >= 20: false
10 <= 20: true
Double comparison:
3.14 == 2.71: false
3.14 != 2.71: true
3.14 > 2.71: true
3.14 < 2.71: false
3.14 >= 2.71: true
3.14 <= 2.71: false
String comparison:
Apple.equals(Banana): false
Apple.compareTo(Banana): -1
Apple.equalsIgnoreCase(Banana): false
Object comparison:
Person{name='Alice', age=30} == Person{name='Bob', age=35}: false
Person{name='Alice', age=30}.equals(Person{name='Bob', age=35}): false
Logical comparison:
true && false: false
true || false: true
!(true): false
Grade calculation:
Grade: B
주의사항 및 특징
기본 타입 비교:
- 기본 타입(int, double, char 등)은 값으로 비교됩니다.
==
연산자는 두 값이 같은지 여부를 판단합니다=
대신==
를 사용해야 합니다.=
는 대입 연산자입니다.
객체 참조 비교:
- 객체를 비교할 때
==
는 객체 참조를 비교합니다. - 객체의 내용을 비교하려면
.equals()
메서드를 사용해야 합니다.
- 객체를 비교할 때
null 비교:
null
과 다른 객체를 비교할 때는==
를 사용할 수 있습니다.obj == null
또는null == obj
형태로 사용합니다.
부동소수점 비교:
- 부동소수점 수를 비교할 때는 주의가 필요합니다.
==
를 사용할 때는 부동소수점 표현의 한계로 인해 예상치 못한 결과가 발생할 수 있습니다.
instanceof 연산자:
- 객체가 특정 클래스나 인터페이스의 인스턴스인지 확인합니다.
object instanceof Class
형태로 사용합니다.
사용 예시:
public class AdvancedComparisonFeatures {
public static void main(String[] args) {
// 기본 타입 비교의 정확성
int x = 5;
int y = 5;
System.out.println("Basic type comparison:");
System.out.println(x + " == " + y + ": " + (x == y));
System.out.println(x + " != " + y + ": " + (x != y));
// 객체 참조 비교와 내용 비교의 차이
String str1 = new String("Hello");
String str2 = new String("Hello");
String str3 = "Hello";
System.out.println("\nObject reference vs content comparison:");
System.out.println(str1 + " == " + str2 + ": " + (str1 == str2)); // false
System.out.println(str1 + ".equals(" + str2 + "): " + str1.equals(str2)); // true
System.out.println(str1 + " == " + str3 + ": " + (str1 == str3)); // false
System.out.println(str1 + ".equals(" + str3 + "): " + str1.equals(str3)); // true
// null 비교의 안전성
Object obj = null;
System.out.println("\nNull comparison safety:");
System.out.println(obj + " == null: " + (obj == null));
try {
System.out.println("obj.toString(): " + obj.toString()); // NullPointerException 발생
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred");
}
// 부동소수점 비교의 불확실성
double d1 = 0.1;
double d2 = 0.2;
System.out.println("\nFloating-point comparison uncertainty:");
System.out.println(d1 + " + " + d2 + " == 0.3: " + ((d1 + d2) == 0.3)); // false
System.out.println("Math.abs((d1 + d2) - 0.3) < 1e-9: " + (Math.abs((d1 + d2) - 0.3) < 1e-9)); // true
// instanceof 연산자의 유용성
Object objInstance = "Hello";
System.out.println("\ninstanceof operator usefulness:");
System.out.println(objInstance + " instanceof String: " + (objInstance instanceof String));
// 복잡한 비교의 성능 고려사항
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
if ("hello".equals("world")) {}
}
long endTime = System.currentTimeMillis();
System.out.println("\nComplex comparison performance consideration:");
System.out.println("Time taken for string comparison loop: " + (endTime - startTime) + " ms");
// 문자열 비교의 대소문자 구분
String strCaseSensitive = "Java";
String strInsensitive = "java";
System.out.println("\nString comparison case sensitivity:");
System.out.println(strCaseSensitive + ".equals(" + strInsensitive + "): " + strCaseSensitive.equals(strInsensitive));
System.out.println(strCaseSensitive + ".equalsIgnoreCase(" + strInsensitive + "): " + strCaseSensitive.equalsIgnoreCase(strInsensitive));
}
}
출력 결과는 다음과 같습니다:
Basic type comparison:
5 == 5: true
5 != 5: false
Object reference vs content comparison:
Hello == Hello: false
Hello.equals(Hello): true
Hello == Hello: false
Hello.equals(Hello): true
Null comparison safety:
null == null: true
NullPointerException occurred
Floating-point comparison uncertainty:
0.1 + 0.2 == 0.3: false
Math.abs((d1 + d2) - 0.3) < 1e-9: true
instanceof operator usefulness:
Hello instanceof String: true
Complex comparison performance consideration:
Time taken for string comparison loop: X ms (X는 실행 환경에 따라 다름)
String comparison case sensitivity:
Java.equals(java): false
Java.equalsIgnoreCase(java): true
편히 모아진 글 보시려면 아래 위키독스 링크 >>
https://wikidocs.net/book/17111
'JAVA' 카테고리의 다른 글
JAVA instanceof 연산자 [코딩백과 with JAVA] (0) | 2024.12.21 |
---|---|
JAVA 조건 연산자 [코딩백과 with JAVA] (0) | 2024.12.21 |
JAVA 단항 연산자 [코딩백과 with JAVA] (0) | 2024.12.21 |
자바 산술 연산자 [코딩백과 with JAVA] (1) | 2024.12.21 |
자바 연산자 소개, 대입 연산자 [코딩백과 with JAVA] (0) | 2024.12.21 |