Possible Duplicate:
Difference in & and &&
if (true && true) {
System.out.println("test if");
}
if (true & true) {
System.out.println("test if");
}
both are give same output.why ?
Possible Duplicate:
Difference in & and &&
if (true && true) {
System.out.println("test if");
}
if (true & true) {
System.out.println("test if");
}
both are give same output.why ?
&&
short-circuits, wheras &
doesn't. Example:
if (methodA() && methodB()) {
...
}
In that case, if methodA
already returns false, methodB
is not called. Formally, if you have an expression a && b
, b
is only evaluated if a
evaluated to true
.
Apart from the obvious performance benefit, this is particularly useful for null
checks:
if (x != null && x.getSomeValue()) {
...
}
If you used a s single &
here, x.getSomeValue()
would be evaluated even if x
were null
, resulting in an exception.
In the first case, you don't test the second part of the if : the &&
operator executes from left to right and stops at the first false
value.
This may be useful in this case :
if (a!=null && a.doSomething()==23) {
because it prevents a nullPointerException.
When you test boolean conditions, always use &&
.
Please see: http://www.jguru.com/faq/view.jsp?EID=16530
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error should occur.
In & statetment it will check both left side and right side statements.in && will check only one side of statement(if one side is true it will not check other side)
&& is the logical AND
so you want to make sure BOTH statements become true.
& is the bitwise AND operator
Have a look here:
&& is logical and. true && true is true and everything else is false. & is bitwise and. (10 & 8) = 8