×

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

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.