English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Difference and Examples of java & and &&

Difference between Java & and &&: & is both a bitwise operator and a logical operator. The operands on both sides of & can be int or boolean expressions. When the operands on both sides of & are int, the numbers on both sides of the operator must be converted to binary numbers before the operation. While the operands on both sides of the short-circuit and (&&) must be boolean expressions.

Many people may encounter this when learning Java or during interviews

& and &&

However, if you do not truly understand their meanings, it will bring you a lot of trouble in your thinking

After reading this blog, you will find it easy to distinguish them

This is my demo

 /**
   *
   */
  package com.b510.test;
 
  /**
   * @author Jone Hongten
   * @create date:2013-11-2
   * @version 1.0
  */
 public class Test {
 
     public static void main(String[] args) {
         String str = null;
        if(str != null && !"".equals(str)){
             //do something
         }
         if(str != null & !"".equals(str)){
             //do something
         }
     }
 }

Now we may have some confusion, let's first look at the circuit problems of & and &&:

For: &&

if(str != null && !"".equals(str))

When str != null, then the next step will be to execute: !"".equals(str)

If str != null is false, then at this time, the program is in a short-circuit situation, then, !"".equals(str) will not be executed.

But for: &

if(str != null & !"".equals(str))

No matter how the result of str != null is (that is, true, false), the program will always execute: !"".equal(str)

Summary of circuit problems:

For: &   -- No matter what, the program on both sides of the symbol "&" will be executed

For: && -- Only when the program on the left of the symbol "&&" is true (true), will the program on the right of the symbol "&&" be executed.

Let's talk about the operation rules:

For: &  -- If either side of the symbol is false, it is false; only when all are true, the result is true

For: && -- If the symbol on the left is false, the result is false; when the left is true, and the right is also true, then the result is true

Thank you for reading, I hope it can help everyone, thank you for your support to our website!

You May Also Like