본문 바로가기
(Pre-class)

Logical operator?

by coramdeo643 2025. 3. 30.

1. Used to mix with the relaitional operator

2. Return a boolean results, True or False, as the relational operator

&& (AND) || (OR) ! (NOT)
x = (a > b) && (c > d); x = (a > b) || (c > d); x = !(a > b);
int a = 5;
int b = 7; 
-------------------------------------------------
boolean c = (a > 2) && (b > 3); // T && T = T
System.out.println(c); // true
-------------------------------------------------
boolean d = (a < 4) && (b > 5); // F && T = F
System.out.println(d); // false
-------------------------------------------------
boolean e = (a > 1) || (b > 0); // T || T = T
System.out.println(e); // true
-------------------------------------------------
boolean f = (a > 6) || (b < 9); // F || T = T
System.out.println(f); // true
-------------------------------------------------
System.out.println(!f); // false
System.out.println(!d); // true
-------------------------------------------------

 

3. Short circuit evaluation

// if the first condition is enough for the value evaluation, it passes and ignores the second condition

3-1. && (AND)

// first false, skip the second(it is already false)

3-2. || (OR)

// first true, skip the second(it is already true)

int a = 5;
int b = 10;
boolean c = ((a += 10) > 100) && ((b -= 5) < 100);
System.out.println(c); // false
System.out.println(a); // 15
System.out.println(b); // 10 (skipped)
----------------------------------------------------
boolean d = ((a += 20) < 100) || ((b *= 3) < 10);
System.out.println(d); // true
System.out.println(a); // 35
System.out.println(b); // 10 (skipped again)

 

4. Ternary operator

// return a or b instead of true or false

// x = (y > z) ? a : b;

int a = (10 > 5) ? 1 : 2;
System.out.println(a); // 1
--------------------------------
char b = (30 > 40) ? 'A' : 'B';
System.out.println(b); // B
--------------------------------
double c = (100 != 200) ? 0.3 : 0.1;
System.out.println(c); // 0.3

'(Pre-class)' 카테고리의 다른 글

If and If else?  (0) 2025.03.31
import java.util.Scanner?  (0) 2025.03.30
Relational Operator?  (0) 2025.03.29
Compound Assignment Operator?  (0) 2025.03.29
Increment and Decrement Operator?  (0) 2025.03.29