Logical Operators in Java

In Java, logical operators are used to determine the logic between variables or values. Logical operators are used to check whether an expression is true or false.

OperatorDescription
&& (Logical AND)Returns true if both statements are true.
|| (Logical OR)Returns true if one of the statements is true.
! (Logical NOT)Reverse the result, returns false if the result is true and vice versa.

1. 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.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		int a = 10, b = 5;
		
		boolean result1 = a > 3 && b > 2;
		System.out.println("result 1: " + result1);
		
		boolean result2 = a > 30 && b > 2;
		System.out.println("result 2: " + result2);
	}

}
result 1: true
result 2: false
 

2. Logical “OR” Operator (||)

This operator returns true when one of the two conditions under consideration is satisfied or is true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		int a = 10, b = 5;
		
		boolean result1 = a > 3 || b > 2;
		System.out.println("result 1: " + result1);
		
		boolean result2 = a > 30 || b < 2;
		System.out.println("result 2: " + result2);
	}

}
result 1: true
result 2: false
 

3. Logical “NOT” Operator (!)

This operator is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition.

    package octopuscodes.com.demo;
    
    public class Demo {
    
    	public static void main(String[] args) {
    		int a = 10, b = 5;
    		
    		boolean result1 = !(a > 3 || b > 2);
    		System.out.println("result 1: " + result1);
    		
    		boolean result2 = !(a > 30 || b < 2);
    		System.out.println("result 2: " + result2);
    	}
    
    }
    result 1: false
    result 2: true