논리 연산자는 피연산자(operand)의 값을 평가하여 결과로 true 또는 false값을 반환한다.
이를 활용한 예제는 다음과 같다.
public class _04_Operator4 {
public static void main(String[] args) {
// 논리 연산자
boolean 김치찌개 = true;
boolean 계란말이 = true;
boolean 제육볶음 = true;
System.out.println(김치찌개 || 계란말이 || 제육볶음); // 하나라도 true 이면 true (괜찮은 식당)
System.out.println(김치찌개 && 계란말이 && 제육볶음); // 모두 true 이면 true (최고의 식당)
// And 연산
System.out.println((5 > 3) && (5 > 1)); // true
System.out.println((5 > 3) && (3 < 1)); // false
// Or 연산
System.out.println((5 > 3) || (3 > 1)); // true
System.out.println((5 > 3) || (3 < 1)); // true
System.out.println((5 < 3) || (3 < 1)); // false
// 논리 부정 연산자
System.out.println(!true); // false
System.out.println(!false); // true
System.out.println(!(5 == 5)); // false
System.out.println(!(5 == 3)); // true
}
}
3개의 피연산자 (operand) 가진 3항 연산자 “:?“는 선택문의 if-when-else 문을 축약해서 사용할 수 있다.
결과 = 조건 ? 수식1(조건이 true인 경우) : 수식2 (조건이 false인 경우)
조건을 평가하여 true인지 false인지 판별하여 true이면 수식1을 false이면 수식2를 실행하여 결과가 반환된다.
조건문(if) 대신에 대입 연산자와 함께 유용하게 사용된다.
이를 활용한 예제는 다음과 같다.
public class _05_Operator5 {
public static void main(String[] args) {
// 삼항 연산자
// 결과 = (조건) ? (참의 경우 결과값) : (거짓의 경우 결과값)
int x = 3;
int y = 5;
int max = (x > y) ? x : y;
System.out.println(max); // 5
int min = (x < y) ? x : y;
System.out.println(min); // 3
boolean b = (x == y) ? true : false;
System.out.println(b); // false
String s = (x != y) ? "달라요" : "같아요";
System.out.println(s); // 달라요
}
}