Classes/Objects  «Prev 


Java Logical Operators

Operator Description Example Result
< Less than 1 < 2 true
<= Less than or equal 1 <=1 true
> Greater than 1 > 2 false
>= Greater than or equal 1 >=1 true
== Is equal to 1==2 false
!= Is not equal to 1 !=2 true
instanceof Is an instance of type "xyz" instanceof String true
& Logical and true & false false
| Logical or true | false true
^ Exclusive or true ^ false true
! Logical not !true false
&& Short-circuit and true && false false
|| Short-circuit or true || false true

Java Language Reference

Logical operators

Logical operators are used to evaluate one or more expressions. These expressions should return a boolean value. You can use the logical operators AND, OR, and NOT to check multiple conditions and proceed accordingly.
If you wish to proceed with a task when both the conditions are true, use the logical AND operator, &&. If you wish to proceed with a task when either of the conditions is true, use the logical OR operator, ||. If you wish to wish to reverse the outcome of a boolean value, use the negation operator, !.
int a = 10;
int b = 20;
System.out.println(a > 20 && b > 10);  //line 1
System.out.println(a > 20 || b > 10);  //line 2
System.out.println(! (b > 10));        //line 3
System.out.println(! (a > 20));        //line 4

Line 1 prints false because both the conditions, a > 20 and b > 10, are not true. The first one (a > 20) is false.
Line 2 prints true because one of these conditions (b > 10) is true.
Line 3 prints false because the specified condition, b > 10, is true. Line 4 prints true because the specified condition, a > 20, is false.
Outcome of using boolean literal values with the logical operators AND, OR, and NOT
Table 4.2 Outcome of using boolean literal values with the logical operators AND, OR, and NOT