×

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two categories. When they operate, they both employ Boolean values and evaluate to Boolean values. The terms "Boolean operators" and "logical operators" refer to operators that do and do not short-circuit, respectively.

Short-circuit and not-short-circuit logical operator work logically on Boolean expressions, but the former only evaluates the latter expression when it is essential. For instance, if you want to do a logical AND between expr-1 and expr-2, the result will always be false if expr-1 returns false, regardless of what expr-2 returns. If Expr-2 in the example is disregarded, the outcome of the AND operation won't be affected. It speeds up the procedure. In contrast, the not-short circuit logical operation executes all Boolean expressions that are submitted for execution.

When a logical expression is evaluated using Java logical operators and ends before it has fully evaluated, this is referred to as a short-circuit. A short circuit occurs when the result is returned even before the expression has been completely evaluated. Short circuit analysis prevents pointless labor and promotes effective processing.

The various types of short circuits that can happen in Java are listed below:

  1. AND(&&) short circuit:
    Since the result will always be false regardless of the extra criterion, the phrase for AND is tested up until one false result is obtained. When the first operand of an expression with the symbol &&(logical AND) is false, a short circuit occurs, the next expression is not examined, and false is returned.

    The short-circuit operator, often called a logical AND or a conditional AND operator, evaluates its second input under certain conditions. The expression's value is false if the first operand evaluates to false, regardless of the value of the second operand. As a result, to save time, the Java interpreter skips the second operand.

Example: Using the AND(&&) operator to short-circuit.

// Java code that uses the && operator to show short circuiting

import java.io.*;


class AND {


    public static void main(String arg[])


    {


        //Evaluation ends, and false is returned because the first operand is false and the operator is &&.


        if (f && t && t) {


System.out.println("this output”+” was printed”+” due to a short circuit”);


        }


        else {


System.out.println("This output "


                               + "will not "


                               + "be printed");


        }


        // No true will be met before the last condition; hence the entire expression will be evaluated.


        if (f || f || t) {


System.out.println("Given that”+” there won't be”+” a short circuit”);


        }


        else {


System.out.println("this output "


                               + "is "


                               + " printed");


        }


  }


}

Output

Actually, a short circuit caused this output to print. Due to the absence of a short circuit, this output is printed.

  • OR(||) short circuit:
  • The expression is tested until only one true result is found because, regardless of the additional criteria, the result of OR is always true. When the first operand of an expression is true and the symbol ||(logical OR) is present, a short circuit occurs, the evaluation is halted, and the value true is returned.

Example: Short-circuiting using OR( || ).

// A Java application that uses OR to show short circuiting


class OR {


    public static void main(String arg[])


    {


        // Evaluation comes to an end, and true is returned since the first operand is true and the operator is ||.


        if (t || f || f) {


System.out.println("this output”+” was printed”+” due to a short circuit”);


        }


        else {


System.out.println("This output "


                               + "will not "


                               + "be printed");


        }


        // No true will be met before the last condition; hence the entire expression will be evaluated.


        if (f || f || t) {


System.out.println("Given that”+” there won't be”+” a short circuit”);


        }


        else {


System.out.println("this output "


                               + "is "


                               + " printed");


        }


    }


}

Output

Actually, this output was printed due to a short circuit. Given that there won't be a short circuit, this output is printed.


Related Topics

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.