Logical Operators in Java

In Java, logical operators are used to perform logical operations on boolean expressions. There are three logical operators in Java. See the list of logical operators in Java below:

OperatorMeaningExampleDescription
&&Short-circuit ANDa && bReturns true if both are true. If a is false b will not be evaluated and returns false.
||Shirt-circuit ORa || bReturns true if anyone is true. If a is true, b will not be evaluated and returns true.
!Logical unary NOT!aReturns true if a is false.

The AND operator (&&) is used to test if two expressions are true. It returns true if both expressions are true, and false if either expression is false. For example:

boolean result = (5 > 3) && (10 < 20);
// result is true because both expressions are true

The OR operator (||) is used to test if at least one of two expressions is true. It returns true if either expression is true, and false if both expressions are false. For example:

boolean result = (5 > 3) || (10 > 20);
// result is true because the first expression is true

The NOT operator (!) is used to negate a boolean value. It returns the opposite boolean value of the expression it operates on. For example:

boolean result = !(5 > 3);
// result is false because the expression 5 > 3 is true

It is important to note that the AND operator has a higher precedence than the OR operator. This means that the AND operator will be evaluated before the OR operator. For example:

boolean result = (5 > 3) && (10 > 20) || (2 < 4);
// result is true because the OR operator returns true

In the example above, the AND operator is evaluated first, resulting in false. However, the OR operator is then evaluated, and because the second expression is true, the overall result is true.

Logical operators are commonly used in control structures such as if-else statements and while loops to control the flow of a program. They are an essential part of programming in Java and are used frequently in a wide range of applications.

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x