Operators in Java: Short-Circuit Logical Operators and Ternary Operator

Java allows its users to operate with the help of a multitude of operators. These are classified as Arithmetic operators, Bitwise operators, Relational Operators, Boolean Logical Operators, Assignment Operators and Ternary Operator. In this tutorial, we shall learn about the Short-circuit logical operator(falls under Boolean Logical Operator) and Ternary Operator.

Short-Circuit Logical Operators

Below table describes four of Java’s boolean operators:

 Symbol Meaning Short Circuit ?
 && and Yes
 &and No
||or Yes
 | or No


Java
exclusively provides the Short-circuit logical operators that are not found in most other languages. These operators fall under the Boolean Logical Operators(&, |, ! etc) and are very similar in operation. There are two Short circuit logical operators: && and ||. They are the secondary versions of the Logical AND operator and the Logical OR operator respectively. Let us first consider the Logical AND and Logical OR.

A B A | BA || B A & BA && B
 False False False False FalseFalse
 TrueFalse TrueTrue FalseFalse
FalseTrue TrueTrue FalseFalse
 True True TrueTrue TrueTrue

As we can see from the above table that the OR operator results in true whenever the value of A is true, without taking into consideration the value of B. Similarly, the AND operator results in false whenever A is false, without taking into consideration the value of B. Thus, Java need not bother about the right-hand side operator if the result can be evaluated by the left-hand operand alone. So, the use of && and || in such cases makes it easier to operate on such operands where the right-hand operand(condition on the right) depends upon the left-hand operand(condition on the left). Let us consider the following example:

package com.codingeek.java.operators;

/*
 *The following program shows the use of the secondary Logical AND and OR(Short-circuit operators)
 */
public class ShortCircuitOperator {
	 
	 public static void main(String args[]) {
		 int a = 3, b = 5, c = 0;
		 
		 //the || operator only checks the left hand side, so the value of b remains unchanged
		 if(a != 0 || b++ > 0) {
			 System.out.println("(a != 0 || b++ > 0) is true and value of b is : " + b);
		 } else {
			 System.out.println("(a != 0 || b++ > 0) is false");
		 }
		 
		 System.out.println();
		 
		 //the | operator checks both the operands and increments the value of b
		 if(a != 0 | b++ > 0) {
			 System.out.println("(a != 0 | b++ > 0) is true and value of b is : " + b);
		 } else {
			 System.out.println("(a != 0 | b++ > 0) is false");
		 }
		 
		 System.out.println();
		 
		 //The && operator only checks the left hand side thus it does not reveal any exceptions
		 if(a != 3 && (a / c) > 5) {
			 System.out.println("(a != 3 && (a / c) > 5) is true");
		 } else {
			 System.out.println("(a != 3 && (a / c) > 5) is false");
		 }
		 System.out.println();
		 
		 //the & operator checks both the operands and it reveals exception in the thread
		 if(a != 3 & (a / c) > 5) {
			 System.out.println("(a != 3 & (a / c) > 5) is true");
		 } else {
			 System.out.println("(a != 3 & (a / c) > 5) is false"); 
		 }
	}
 }

Output:-
(a != 0 || b++ > 0) is true and value of b is : 5

(a != 0 | b++ > 0) is true and value of b is : 6

(a != 3 && (a / c) > 5) is false

Exception in thread "main" java.lang.ArithmeticException: / by zero at com.codingeek.java.operators.ShortCircuitOperator.main(ShortCircuitOperator.java:32)

Here we see that the program prints 10 despite the increment operation performed on b. The reason is that the logical operator || evaluates the boolean result by simply looking at the left-hand expression which is true so the output must also be true. So, the control does not go to the right-hand side expression.

Note: For boolean operations, we usually use the secondary versions of the Logical operators AND and OR. And the singular AND and OR are used for bitwise operations. Although it is not necessary to stick to this rule, there might be exceptions where the singular operators can be used for boolean cases as well.


The Ternary Operator

Ternary operators can be used to replace some of the if-else statement.It takes three operands or expressions and reduces the lines of code greatly. Its general form is shown below:

expression1 ? expression2 : expression3;

Here expression1 contains any expression which yields a boolean result. If the result is true then expression2 is evaluated otherwise expression3 is evaluated. So first the control goes to expresion1 which yields a boolean value and then the result is evaluated from expression2 and expression3 accordingly. It is important to note that both expression2 and expression3 should be of same or compatible types and not void.  Here is an example which shows the use of ternary operator:

/**
 * This program finds out the maximum of the two numbers using ternary operator
 */

import java.util.Scanner;

public class TernaryOperator {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int a, b, max;
        System.out.println("Enter two numbers : ");
        a = in.nextInt();
        b = in.nextInt();

        //The max is evaluated using the ternary operator which shall
        //result in true or false according to the user input.
        max = (a > b) ? a : b;
        System.out.println("The max number is : " + max);
    }
}


Output:-
Enter two numbers : 
34
72
The max number is : 72

An investment in knowledge always pays the best interest. Hope you like the tutorial. Do come back for more because learning paves way for a better understanding.

Do not forget to share and Subscribe.

Happy coding!! 🙂

Recommended -