Java Logical Operators Shortcut

In this chapter you will learn:

  1. What is Java Logical Operators Shortcut
  2. Example - Short-Circuit Logical Operators in Java
  3. Example - Not Shortcut Logical Operators

Description

The OR operator results in true when one operand is true, no matter what the second operand is. The AND operator results in false when one operand is false, no matter what the second operand is. If you use the || and &&, Java will not evaluate the right-hand operand when the outcome can be determined by the left operand alone.

Example

The following code shows how you can use short-circuit logical operator to ensure that a division operation will be valid before evaluating it:

 
public class Main {
  public static void main(String[] argv) {
    int denom = 0;
    int num = 3;//  w ww .  ja va2  s.c o  m
    if (denom != 0 && num / denom > 10) {
      System.out.println("Here");
    } else {
      System.out.println("There");
    }
  }
}

The output:

Example 2

If we want to turn of the shortcut behaviour of logical operators we can use & and |.

The following code uses a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

 
public class Main {
  public static void main(String[] argv) {
    int c = 0;/*from ww w. j  a  v a2 s.com*/
    int e = 99;
    int d = 0;
    if (c == 1 & e++ < 100)
      d = 100;

    System.out.println("e is " + e);
    System.out.println("d is " + d);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What are the relational operators in Java
  2. Relational Operators List
  3. Example - Java Relational Operators
  4. Example - outputs the result of a relational operator
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator