and, or, and not are logical operators used to combine or modify boolean expressions. They play a crucial role in controlling program flow and decision-making.
AND (&&)
The && operator returns true if both operands are true; otherwise, it returns false.
It exhibits short-circuiting behavior, meaning that if the left operand evaluates to false, the right operand is not evaluated.
OR (||)
The || operator returns true if at least one of the operands is true; it returns false only if both operands are false.
It also exhibits short-circuiting behavior: if the left operand is true, the right operand is not evaluated.
NOT (!)
The ! operator is a unary operator that inverts the boolean value of its operand. If the operand is true, ! returns false, and vice-versa.
Here is a table summarizing the behavior of these operators:
Example of Logical Operators in Java
Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for all the situations.
a = 10, b = 20, c = 30
For AND operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [Both Conditions are true]
For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [One of the Condition if true]
For NOT Operator:
Condition 1: c > a
Condition 2: c > b
Output:
False [Because the result was true and NOT operator did it's opposite]
Logical AND Operator (&&) with Example
This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. In Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).
Syntax:
condition1 && condition2
Illustration:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b == c
if(condition1 && condition2)
d = a + b + c
// Since both the conditions are true
d = 50.
Reffer::
https://www.geeksforgeeks.com
Top comments (0)