Logical ‘AND’ Operator (&&)
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.
Example:
// Java code to illustrate
// logical AND operator
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
// using logical AND to verify
// two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}
Output
Var1 = 10 Var2 = 20 Var3 = 20 The sum is: 50
Now in the below example, we can see the short-circuiting effect. Here when the execution reaches to if statement, the first condition inside the if statement is false and so the second condition is never checked. Thus the ++b(pre-increment of b) never happens, and b remains unchanged.
Example:
import java.io.*;
class shortCircuiting {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 15;
// displaying b
System.out.println("Value of b : " + b);
// Using logical AND
// Short-Circuiting effect as the first condition is
// false so the second condition is never reached
// and so ++b(pre increment) doesn't take place and
// value of b remains unchanged
if ((a > c) && (++b > c)) {
System.out.println("Inside if block");
}
// displaying b
System.out.println("Value of b : " + b);
}
}
Output:
Java Logical Operators with Examples
Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first one is false. Whereas while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND and OR operators have a short-circuiting effect. Used extensively to test for several conditions for making a decision.
- AND Operator ( && ) – if( a && b ) [if true execute else don’t]
- OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t]
- NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]