Java - Logical Short-Circuit OR Operator ||

What is Logical Short-Circuit OR Operator?

The logical short-circuit OR operator ( ||) is used in the form

operand1 || operand2 
  

The logical short-circuit OR operator returns true if either operand is true.

If both operands are false, it returns false.

If operand1 evaluates to true, it returns true without evaluating operand2. This is why it is called a short-circuit OR operator.

Example

The following code shows how to Logical Short-Circuit OR Operator.

int i = 10; 
int j = 15; 
boolean b = (i > 5 || j > 10); // Assigns true to b 

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10; /* w w w.j  a v  a 2 s .  c  om*/
    int j = 15; 
    boolean b = (i > 5 || j > 10); // Assigns true to b 
    System.out.println ("b = " + b); 

  }
}

Result

Consider another example.

int i = 10; 
int j = 15; 
boolean b = (i > 20 || j > 10); // Assigns true to b 
  

The expression i > 20 returns false. The expression reduces to false || j > 10.

Because the left-hand operand to || is false, the right-hand operand, j > 10, is evaluated, which returns true and the entire expression returns true.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10; /*from w w  w  . j  ava2 s  . c  o m*/
    int j = 15; 
    boolean b = (i > 20 || j > 10); // Assigns true to b 

    System.out.println ("b = " + b); 

  }
}

Result