Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Conditional Operators

A conditional operator shows the relationship of 2 or more boolean expressions. There are only 2 kinds of conditional operators. It is the AND condition which is represented by double ampersand (&&) symbol, and the OR condition which is represented by double pipe (||) symbol.

  package com.example.core;

  /**
   * This will demonstrate how to use conditional AND and 
   * conditional OR.
   * 
   * @author Rolan Liwanag
   *
   */
  public class AndOr {

    public static void main(String[] args) {
	  double aDouble = 2.0;
	  double bDouble = 2.0;
	  //Double ampersand is how to implement an 
	  //AND condition in Java
	  if(aDouble == 2 && bDouble == 2) {
	    System.out.println("Both aDouble and bDouble are " 
	      + "equal to 2.");
	  }
	  /*
	   * When we use AND as a condition to relate 2 or 
	   * more boolean expressions, it means, all conditions 
	   * should be met. In the above example, if it 
	   * happened that either aDouble or bDouble is not 
	   * equal to 2, then, it will not execute whatever 
	   * line of codes that are inside the if block.
	   */
	  long aLong = 1;
	  long bLong = 2;
	  //Double pipe is how to implement an 
	  //OR condition in Java.
	  if(aLong == 2 || bLong == 2) {
        System.out.println("Either aLong or bLong must " 
          + "have been equal to 2.");
	  }
	  /*
	   * When we use OR as a condition to relate 2 or more 
	   * boolean expressions, it means, at least one  
	   * condition among the series of boolean expressions 
	   * must be met.
	   */
    }
  }
                           
To summarize things, this is how things work for each operator.
true && true = true
true && false = false
false && true = false
false && false = false
true || true = true
true || false = true
false || true = true
false || false = false


Back    Next