I think a lot of people are learning Java, or other languages (such as C #,. NET, etc.) will encounter
& and &&
However, if you don't really understand what they mean, it's going to give you a lot of trouble with your ideas.
In this blog, when you have finished reading, you will find that it is easy to distinguish them from the
Here's my demo.
1/**2*3*/4PackageCom.b510.test;56/**7*@authorJone Hongten8* @create Date:2013-11-29*@version1.010*/11PublicClassTest {1213PublicStaticvoidMain (string[] args) {String str = null; if (str! = null &&! "" .equals (str)) {16 //do something< Span style= "color: #008080;" >17 }18 if (str! = null &! "" .equals (str)) {19 //do something< Span style= "color: #008080;" >20 }21 }22}
We may have some ambiguity now, so let's take a look at the circuit problems of & and &&:
For:&&
Null &&! "". Equals (str))
When: str = NULL, the next step is to execute:! "". Equals (str)
if: str! = is NULL for false, then this time, the program is in a short-circuit case, then, "". Equals (str) is not executed.
But for:&
Null &! "". Equals (str))
Regardless of the result of str! = NULL (that is, True,false), the program will execute:! "". Equal (str)
Circuit Problem Summary:
For:&-> Anyway, the "&" symbol will be executed on both sides of the program
For:&&-> The program to the right of the symbol "&&" is executed only if the symbol "&&" to the left of the program is True (TRUE).
Here are the arithmetic rules:
For:&-> False if there is a false on both sides of the left and right, and true when all is true
For:&&-> If the left side of the symbol is false, the result is false; true on the left and true on the right.
Extension:
| ----> True if there is a true on both sides, false if all is False
|| --> The result is true if the left side of the symbol is true; false on the left and false on the right.
As an example:
int i=0;
if (3>2 | | (i++) >1) i=i+1;
System.out.println (i);// The result is 1 .
int i=0;
if (3>2 | (i++) >1) i=i+1;
System.out.println (i);// The result is 2 .
Let's take another look:
Also & is the bitwise operator (with) "| or, ~ Non, ^ xor"
And the operator is denoted by the symbol "&", which uses the following rules:
The two operands have a bit of 1 and the result is 1, otherwise the result is 0, for example, the following program segment.
public class Data13
{
public static void Main (string[] args)
{
int a=129;
int b=128;
System.out.println ("A and B" with the result is: "+ (a&b));
}
}
Run results
A and B with the result is: 128
The following analysis of this program:
The value of "a" is 129, converted to binary is 10000001, and the value of "B" is 128, converted to binary is 10000000. According to the operator's operation Law, only two bits are 1, the result is 1, you can know the result is 10000000, that is, 128.
However, && does not have this feature.
Reproduced in: http://www.cnblogs.com/hongten/p/hongten_java_yu.html
& and && in Java