boolean 자료형
boolean
자료형
boolean
자료형참/거짓 둘 중 한 값을 가짐
1바이트 (8비트) 공간 차지
하드웨어 구조와의 호환성 - CPU가 수월히 다룰 수 있는 최소 단위
리터럴보다는 반환값으로 많이 사용됨
부정 연산자
!
:boolean
의 값을 반전
package sec03.chap04;
public class Ex01 {
public static void main(String[] args) {
boolean bool1 = true;
boolean bool2 = false;
boolean bool3 = !true;
boolean bool4 = !false;
boolean bool5 = !!bool3;
boolean bool6 = !!!bool3;
boolean bool7 = !(1 > 2);
boolean bool8 = !((5 / 2) == 2.5);
boolean bool9 = !((3f + 4.0 == 7) != ('A' < 'B'));
}
}
IntelliJ에서 비교 연산자에 커서를 가져다 대면 단위별로 true , false 가 표시됨
논리 연산자
a && b
AND
a와 b가 모두 true일때만 true 반환
a || b
OR
a와 b 중 하나만 true면 true 반환
package sec03.chap04;
public class Ex02 {
public static void main(String[] args) {
boolean bool1 = true && true;
boolean bool2 = true && false;
boolean bool3 = false && true;
boolean bool4 = false && false;
boolean bool5 = true || true;
boolean bool6 = true || false;
boolean bool7 = false || true;
boolean bool8 = false || false;
int num = 6;
// 💡 &&가 ||보다 우선순위 높음
boolean boolA = (num % 3 == 0) && (num % 2 == 0) || (num > 0) && (num > 10);
boolean boolB = (num % 3 == 0) && ((num % 2 == 0) || (num > 0)) && (num > 10);
}
}
단축평가 short circuit
&&
: 앞의 것이false
면 뒤의 것을 평가할 필요 없음||
: 앞의 것이true
면 뒤의 것을 평가할 필요 없음평가는 곧 실행 - 이 점을 이용한 간결한 코드
💡 연산 부하가 적은 코드를 앞에 - 리소스 절약
package sec03.chap04;
public class Ex03 {
public static void main(String[] args) {
int a = 1, b = 2, c = 0, d = 0, e = 0, f = 0;
boolean bool1 = a < b && c++ < (d += 3);
boolean bool2 = a < b || e++ < (f += 3);
boolean bool3 = a > b && c++ < (d += 3); // 🔴
boolean bool4 = a > b || e++ < (f += 3);
}
}
삼항 연산자
a
?
b:
ca : 불리언 값
b : a가
true
일 때 반환될 값c : a가
false
일 때 반환할 값
package sec03.chap04;
public class Ex04 {
int num1 = 3, num2 = 4;
char num1OE = num1 % 2 == 1 ? '홀' : '짝';
char num2OE = num2 % 2 == 1 ? '홀' : '짝';
}
문제풀기
Last updated