Java logical operators are used to perform logical operations on boolean values. These operators are commonly used in decision-making statements such as if
conditions and loops to control program flow.
The following table lists the logical operators in Java:
Operator Description Example && (Logical AND) Returnstrue
if both operands are true
, otherwise returns false
. (A && B)
returns true
if both A and B are true. || (Logical OR) Returns true
if at least one of the operands is true
. (A || B)
returns true
if either A or B is true. ! (Logical NOT) Reverses the logical state of the operand. !A
returns true
if A is false
, and false
if A is true
.
The following programs are simple examples which demonstrate the logical operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −
Example 1In this example, we're creating two variables a and b and using logical operators. We've performed a logical AND operation and printed the result.
public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a && b = " + (a&&b)); } }Output
a && b = falseExample 2
In this example, we're creating two variables a and b and using logical operators. We've performed a logical OR operation and printed the result.
public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a || b = " + (a||b) ); } }Output
a || b = trueExample 3
In this example, we're creating two variables a and b and using logical operators. We've performed a logical Negate operation and printed the result.
public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("!(a && b) = " + !(a && b)); } }Output
!(a && b) = true
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4