The difference between java & and &&: & is both a bit operator and a logical operator. Both sides of & can be int or boolean expressions. When both sides of & are int, the numbers on both sides of the operator must be converted into binary numbers before performing operations. The two sides of the short circuit and (&&) must be Boolean expressions.
I think many people will encounter it when learning Java or during interviews
&and&&
However, if you don't really understand what they mean, it will cause a lot of trouble in your thinking
In this blog, after you finish reading it, you will find that it is easy to distinguish them
Here 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
}
}
}
We may have some blur now, so let's take a look at the circuit problems of & and &&:
for:&&
if(str != null && !"".equals(str))
When: str != null, the following execution will be performed: !"".equals(str)
If: str != null is false, then at this time, the program is in a short circuit, then !"".equals(str) will not be executed.
But for:&
if(str != null & !"".equals(str))
Regardless of the result of str != null (i.e. true, false), the program will execute: !"".equal(str)
Summary of circuit problems:
For:& --> No matter what, the program on the left and right sides of the "&" symbol will be executed
For: && -- > The program on the right side of the symbol "&&" will be executed only if the program on the left side of the symbol "&&" is true (true).
Let’s talk about the operation rules below:
For: & --> As long as one of the left and right sides is false, it is false; only when all are true, the result is true
For:&& --> As long as the left side of the symbol is false, the result is false; when the left side is true and the right side is true, the result is true
Thank you for reading, I hope it can help you. Thank you for your support for this site!