조건 연산자
Java는 프로그램의 흐름을 제어하고 조건부 로직을 구현하는 데 사용되는 여러 가지 조건 연산자를 제공합니다. 주요 조건 연산자로는 논리 연산자와 삼항 연산자가 있습니다.
논리 연산자 (Logical Operators)
&&
(AND 연산자)||
(OR 연산자)!
(NOT 연산자)
단락 평가(Short-circuit Evaluation)
&&
dhk ||
연산자는 단락 평가 특성을 가집니다. 이는 왼쪽 피연산자가 충분히 결과를 결정할 수 있다면 오른쪽 피연산자를 평가하지 않음을 의미합니다.
사용 예시:
public class ShortCircuitEvaluationDemo {
public static void main(String[] args) {
boolean flag = true;
int count = 0;
if (flag && incrementCount(count)) {
System.out.println("Both conditions are true");
}
System.out.println("Final count: " + count);
flag = false;
count = 0;
if (flag || incrementCount(count)) {
System.out.println("At least one condition is true");
}
System.out.println("Final count after OR operation: " + count);
}
private static boolean incrementCount(int count) {
count++; // 이 줄은 단락 평가로 인해 실행되지 않을 수 있음
System.out.println("incrementCount method called");
return true;
}
}
- && (AND) 연산자의 단락 평가:
첫 번째 조건이 false일 때, 두 번째 조건은 평가되지 않습니다. - || (OR) 연산자의 단락 평가:
첫 번째 조건이 true일 때, 두 번째 조건은 평가되지 않습니다.
출력 결과는 다음과 같습니다:
incrementCount method called
Both conditions are true
Final count: 1
At least one condition is true
Final count after OR operation: 0
삼항 연산자 (Ternary Operator)
삼항 연산자의 형식은 다음과 같습니다:
condition ? expressionIfTrue : expressionIfFalse
사용 예시:
public class TernaryOperatorExample {
public static void main(String[] args) {
int temperature = 25;
String weatherDescription = temperature > 20 ? "Warm" : "Cold";
System.out.println("Today's weather is " + weatherDescription);
int score = 85;
String grade = score >= 90 ? "A" : (score >= 80 ? "B" : "C");
System.out.println("Your grade is " + grade);
String name = "Alice";
String greeting = name.startsWith("A") ? "Good morning, Alice!" : "Hello, " + name + "!";
System.out.println(greeting);
int x = 5;
int y = 3;
int max = x > y ? x : y;
System.out.println("Max value: " + max);
}
}
출력 결과는 다음과 같습니다:
Today's weather is Warm
Your grade is B
Good morning, Alice!
Max value: 5
주의사항 및 특징
단락 평가의 이점:
- 성능 최적화에 유용할 수 있습니다.
- 예를 들어, 첫 번째 조건이 false인 경우 두 번째 조건을 평가하지 않아도 됩니다.
삼항 연산자의 타입 일치:
- 삼항 연산자의 두 번째와 세 번째 피연산자는 같은 타입이어야 하거나 자동으로 변환될 수 있어야 합니다.
논리 부정의 우선순위:
!
연산자는 다른 모든 연산자보다 높은 우선순위를 가집니다.
복잡한 표현식에서의 사용:
- 여러 조건 연산자를 결합하여 조건문을 만들 수 있지만, 코드의 가독성을 해칠 수 있으므로 주의해야 합니다.
삼항 연산자의 사용 시기:
- 간단하고 읽기 쉬운 경우에만 사용하는 것이 좋습니다.
- 특히 표현식이 간결하고 부작용(side-effect)이 없는 경우에 적합합니다.
사용 예시:
public class ConditionalOperatorFeatures {
public static void main(String[] args) {
// 단락 평가의 이점
boolean flag = false;
int count = 0;
if (flag && incrementCount(count)) {
System.out.println("Both conditions are true");
}
System.out.println("Count after short-circuit evaluation: " + count);
// 삼항 연산자의 타입 일치
int x = 5;
double y = 3.5;
double result = (x > y) ? x : y;
System.out.println("Type-compatible ternary result: " + result);
// 논리 부정의 우선순위
boolean condition = true;
System.out.println("!(condition && true): " + (!(condition && true)));
System.out.println("(!condition) && true: " + ((!condition) && true));
// 복잡한 표현식의 가독성 문제
int score = 75;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("Grade: " + grade);
// 삼항 연산자의 적절한 사용
String name = "Alice";
String greeting = (name.startsWith("A")) ? "Good morning!" : "Hello!";
System.out.println(greeting);
// 부작용(side-effect)이 있는 삼항 연산자 사용의 위험성
int[] array = {1, 2, 3};
int index = 0;
int value = (index >= 0 && index < array.length) ? array[index++] : 0;
System.out.println("Value: " + value);
System.out.println("Index after operation: " + index);
}
private static boolean incrementCount(int count) {
count++; // 이 줄은 단락 평가로 인해 실행되지 않을 수 있음
System.out.println("incrementCount method called");
return true;
}
}
출력 결과는 다음과 같습니다:
Count after short-circuit evaluation: 0
Type-compatible ternary result: 5.5
!(condition && true): false
(!condition) && true: false
Grade: C
Good morning!
Value: 1
Index after operation: 1
incrementCount method called
편히 모아진 글 보시려면 아래 위키독스 링크 >>
https://wikidocs.net/book/17111
'JAVA' 카테고리의 다른 글
JAVA 비트 연산자, 시프트 연산자 [코딩백과 with JAVA] (0) | 2024.12.21 |
---|---|
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 |