Boolean Operators
Boolean Operators
Objectives - Boolean
Operators
Boolean operators are operators that return a boolean value (true or false).
Equal To
Java uses the == operator to determine equality. Beginners often confuse
the = and the == operators. Remember, = is the assignment operator.
int a = 5;
int b = 5;
System.out.println(a == b);
challenge
Not Equal To
The != operator checks to see if two values are not equal.
int a = 5;
int b = 5;
System.out.println(a != b);
challenge
Less Than
The < operator is used to check if one value is less than another value.
int a = 5;
int b = 7;
System.out.println(a < b);
challenge
int a = 5;
int b = 7;
System.out.println(a <= b;)
challenge
Greater Than
The > operator is used to check if one value is greater than another value.
int a = 9;
int b = 17;
System.out.println(a > b);
challenge
int a = 9;
int b = 17;
System.out.println(a >= b);
challenge
boolean a = true;
boolean b = true;
boolean c = false;
System.out.println(a && b);
challenge
boolean a = true;
boolean b = true;
boolean c = false;
System.out.println(a && b && c);
challenge
The || Operator
The || operator allows for compound (more than one) boolean expressions.
If only one boolean expressions is true, then the whole thing is true. To be
false, all boolean expressions must be false.
boolean a = true;
boolean b = true;
boolean c = false;
boolean d = false;
System.out.println(a || b);
challenge
Multiple || Statements
You can chain several || statements together. They are evaluated in a left-to-
right manner.
boolean a = true;
boolean b = true;
boolean c = false;
System.out.println(a || b || c);
challenge
System.out.println(a || c || c || c || c);?
The ! Operator
The ! operator produces the opposite of the boolean expression that it
modifies.
System.out.println(! true);
challenge
Short Circuiting
If Java can determine the result of a boolean expression before evaluating
the entire thing, it will stop and return the value.
Short Circuiting
System.out.println( false
&&
/*Java never reaches this line*/ true);
System.out.println( true
||
/*Java never reaches this line*/ false);