×

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

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.