In this tutorial you will learn about the Java Logical Operators and its application with practical example.
Java Logical Operators
Logical operators are used to combine expressions with conditional statements using logical (AND, OR, NOT) operators, which results in true or false. Let variable a hold true or 1 and variable b hold false or 0, then −
Operator | Name | Description | Example |
---|---|---|---|
&& |
Logical AND |
return true if all expression are true |
(a && b) returns false |
|| |
Logical OR |
return true if any expression is true |
(a || b) returns true |
! |
Logical NOT |
return complement of expression |
!a returns false |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Main { public static void main(String[] args) { //Variables Definition and Initialization boolean bool1 = true, bool2 = false; System.out.println("W3Adda - Java Logical Operators"); //Logical AND System.out.println("bool1 && bool2 = " + (bool1 && bool2)); //Logical OR System.out.println("bool1 || bool2 = " + (bool1 | bool2) ); //Logical Not System.out.println("!(bool1 && bool2) = " + !(bool1 && bool2)); } } |
When you run the above java program, you will see the following output.
Output:-