tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Core > Boolean > Short Circuit Evaluations

Short Circuit Evaluations 

This example shows how to use short circuit evaluation operators (&&, ||) and binary operators (&, |)

File Name  :  
com/bethecoder/tutorials/core/bool/ShortCircuitEvaluation.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.core.bool;

public class ShortCircuitEvaluation {

  public static boolean operation1() {
    System.out.println("operation 1");
    return true;
  }
  
  public static boolean operation2() {
    System.out.println("operation 2");
    return true;
  }

  public static boolean operation3() {
    System.out.println("operation 3");
    return false;
  }
  
  public static boolean operation4() {
    System.out.println("operation 4");
    return false;
  }
  
  
  /**
   @param args
   */
  public static void main(String[] args) {
    
    // op1 &  op2  - Evaluates both op1 and op2
    // op1 && op2  - Evaluates op2 only if op1 is TURE
    
    // op1 |  op2  - Evaluates both op1 and op2
    // op1 || op2  - Evaluates op2 only if op1 is FALSE
    
    boolean result = false;
    
    System.out.println("--------------------------");
    result = operation1() & operation2();
    System.out.println(result);
    
    System.out.println("--------------------------");
    result = operation3() && operation2();
    System.out.println(result);
    
    System.out.println("--------------------------");
    result = operation1() && operation2();
    System.out.println(result);
    
    
    
    System.out.println("--------------------------");
    result = operation3() | operation4();
    System.out.println(result);
    
    System.out.println("--------------------------");
    result = operation1() || operation4();
    System.out.println(result);
    
    System.out.println("--------------------------");
    result = operation3() || operation4();
    System.out.println(result);
  }

}
   

It gives the following output,
--------------------------
operation 1
operation 2
true
--------------------------
operation 3
false
--------------------------
operation 1
operation 2
true
--------------------------
operation 3
operation 4
false
--------------------------
operation 1
true
--------------------------
operation 3
operation 4
false



 
  


  
bl  br