SoFunction
Updated on 2025-04-13

Differences, application scenarios and code examples of & && and | and | in Java

Differences, application scenarios and code examples of & && and | and | in Java

Updated: March 25, 2025 11:23:08 Author: 4 liang 1 qian
This article mainly introduces the differences between logical operators &, &&, | and || in Java, including their application on Boolean and integer types. The article introduces the code in a very detailed way. Friends who need it can refer to it.

Preface

In Java, & and && and | and || are logical operators, but they have some important differences in their use. The following is a comprehensive summary of these operators, including their differences, application scenarios, and code examples.

1. & and &&

  • &:
    • Bitwise and operators: When acting on an integer type, it performs bitwise and operations.
    • Logic and operators: When applied to a Boolean type, it evaluates the expression on both sides, regardless of whether the expression on the left is false.
  • &&:
    • Short circuit and operator: When acting on the Boolean type, if the expression on the left is false, the expression on the right is not calculated, and false is directly returned.

Code Example

public class Main {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        // Use &        boolean result1 = a & checkCondition();
        // Output: Result with &: false        ("Result with &: " + result1); 

        // Use &&        boolean result2 = a && checkCondition();
        // Output: Result with &&: false        ("Result with &&: " + result2); 

        // Use &, even if the left is false, the right expression will still be calculated        boolean result3 = b & checkCondition();
        // Output: Result with &: false        ("Result with &: " + result3); 

        // When using &&, if the left is false, the expression on the right will not be calculated        boolean result4 = b && checkCondition();
        // Output: Result with &&: false        ("Result with &&: " + result4); 
    }

    public static boolean checkCondition() {
        ("Checking condition");
        return false;
    }
}

2. | and ||

  • |:
    • bitwise or operator: When acting on an integer type, it performs a bitwise or operation.
    • Logic or operator: When applied to a Boolean type, it evaluates the expression on both sides, regardless of whether the expression on the left is true.
  • ||:
    • Short circuit or operator: When acting on a Boolean type, if the expression on the left is true, the expression on the right is not calculated, and true is directly returned.

Code Example

public class Main {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        // Use |        boolean result1 = a | checkCondition();
        // Output: Result with |: true        ("Result with |: " + result1); 

        // Use ||        boolean result2 = a || checkCondition();
        // Output: Result with ||: true        ("Result with ||: " + result2); 

        // Use |, even if the left is true, the right expression will still be calculated        boolean result3 = b | checkCondition();
        // Output: Result with |: false        ("Result with |: " + result3); 

        // When using ||, the left is true, the expression on the right will not be calculated        boolean result4 = b || checkCondition();
        // Output: Result with ||: true        ("Result with ||: " + result4); 
    }

    public static boolean checkCondition() {
        ("Checking condition");
        return false;
    }
}

3. Why use & and | instead of always using && and ||

Although && and || have short circuit characteristics that can improve efficiency and safety in many cases, in certain specific scenarios, &&| also has its unique advantages:

  • Make sure both expressions are calculated:
    • Logging: Even if the first condition is not met, it is hoped to record the check result of the second condition.
    • Update multiple statuses: Even if the first status update fails, you still want to continue to update other statuses.
    • Multiple side effects operations: Each operation has certain side effects, and I hope to ensure that all operations are performed.
    • Multiple input verification: I hope to continue to verify other input fields even if the first input verification fails

Code Example

public class Main {
    public static void main(String[] args) {
        // Logging        boolean condition1 = checkCondition1();
        boolean condition2 = checkCondition2();
        boolean result1 = condition1 & condition2;
        ("Final result: " + result1);

        // Update multiple statuses        boolean status1 = updateStatus1();
        boolean status2 = updateStatus2();
        boolean result2 = status1 & status2;
        ("Final result: " + result2);

        // Multiple side effects operations        boolean operation1 = performOperation1();
        boolean operation2 = performOperation2();
        boolean result3 = operation1 & operation2;
        ("Final result: " + result3);

        // Multiple input verification        boolean isValid1 = validateInput1();
        boolean isValid2 = validateInput2();
        boolean result4 = isValid1 & isValid2;
        ("Final result: " + result4);
    }

    public static boolean checkCondition1() {
        ("Checking condition 1");
        return true;
    }

    public static boolean checkCondition2() {
        ("Checking condition 2");
        return false;
    }

    public static boolean updateStatus1() {
        ("Updating status 1");
        return true;
    }

    public static boolean updateStatus2() {
        ("Updating status 2");
        return false;
    }

    public static boolean performOperation1() {
        ("Performing operation 1");
        return true;
    }

    public static boolean performOperation2() {
        ("Performing operation 2");
        return false;
    }

    public static boolean validateInput1() {
        ("Validating input 1");
        return true;
    }

    public static boolean validateInput2() {
        ("Validating input 2");
        return false;
    }
}

Summarize

  • && and || are mainly used for Boolean logic operations, with short circuit characteristics, which can improve efficiency and safety.
  • & and | can also be used in bitwise operations, or in case you need to ensure both expressions on the sides are calculated.
  • Choosing the appropriate operator depends on the specific usage scenario and requirements. In most cases, using && and || can avoid unnecessary calculations and potential exceptions, but in scenarios where all expressions are computed, using & and | is more appropriate.
  • &&
  • &

Related Articles

  • Detailed explanation of the implementation of the advanced http protocol Transfer-Encoding and HttpCore

    This article mainly introduces the relevant information of the http protocol Transfer-Encoding and HttpCore implementation. The article introduces it in detail and is believed to have certain reference value for everyone. Friends who need it, let’s take a look together below.
    2017-04-04
  • Summary of the usage examples of this in Java

    This in JAVA is a very important module and plays a very important role in programming. People who are good at using this can often make the program more concise and convenient. The following article mainly introduces relevant information about the usage of this in Java. Friends who need it can refer to it.
    2022-08-08
  • Do you know that annotations in Java can be inherited?

    I believe everyone has used annotations, also known as metadata, which is a code-level annotation that can mark and explain elements such as classes or methods. So today I want to ask you that the class has been inherited. Can the annotation be inherited? It may be different from what everyone thinks. If you are interested, you can read it down
    2022-12-12
  • Springboot jar main manifest attribute loss solution

    This article mainly introduces the Springboot jar main list attribute loss solution. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.
    2020-06-06
  • Detailed explanation of the basics of Java FileInputStream and FileOutputStream

    This article mainly introduces the detailed explanation of the Java basics FileInputStream and FileOutputStream streams. There are very detailed code examples in the article, which are very helpful to friends who are learning Java basics. Friends who need it can refer to it.
    2021-04-04
  • Java example to convert numerical prices to Chinese capital code (tool class)

    This article mainly introduces the relevant information of Java converting digital prices into Chinese capitals. In Java, the conversion of digital prices into Chinese capitals requires decomposing the numbers into various parts (such as single digits, ten digits, hundreds digits, etc.), and converting them into corresponding Chinese capitals based on these parts. Friends who need it can refer to it.
    2024-10-10
  • Int initialization in java can be 0, but not NULL problem

    This article mainly introduces the problem that int initialization can be 0 but not NULL in Java. It has good reference value and hope it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2023-02-02
  • Detailed steps for downloading JDK1.8 source code and importing jdk1.8 source code in idea2021

    This article mainly introduces the detailed steps of JDK1.8 source code download and idea2021 import jdk1.8 source code. At the beginning of the article, I will share with you the download address and download steps of JDK1.8 source code to you, and tell you the steps of idea2021.1.3 import JDK1.8 source code. Friends who need it can refer to it.
    2022-11-11
  • A brief discussion on the various ways to use JSON in Java

    This article mainly introduces a brief discussion on the various ways of using JSON in Java. The article introduces the example code in detail, which has a certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2021-01-01
  • New Java String String Splicing Method Detailed Explanation of the Usage of StringJoiner

    In this article, the editor will share with you a detailed explanation of the usage of StringJoiner on the new Java string splicing method. Readers who need it can refer to it.
    2019-09-09

Latest Comments