As said in thinking in Java if you have 2 boolean objects, x
and y
you can use either x= x&&y
and x=x&y
on them, so why its necessary having both types?
Asked
Active
Viewed 354 times
4

user2428118
- 7,935
- 4
- 45
- 72

Eduardo EPF
- 160
- 10
-
1See also: http://stackoverflow.com/questions/11411907/what-are-the-cases-in-which-it-is-better-to-use-unconditional-and-instead-of – assylias Nov 26 '12 at 12:53
4 Answers
12
The two operators act differently:
&
will always evaluate both operands&&
is short-circuiting - if the first operand evaluates tofalse
, then the overall result will always be false, and the second operand isn't evaluated
See the Java Language Specification for more details:

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
1+1, also, the short-circuiting form is almost always what you will want to use. It's especially useful for avoiding NPEs, like: `if (someVar != null && someVar.getSomeProp() == 1) { ... }` – ach Nov 26 '12 at 14:44
3
Look at the output of this code:
int x = 0;
boolean b = false & (++x == 1); // b is false
System.out.println(x); // prints 1
x = 0;
b = false && (++x == 1); // b is false
System.out.println(x); // prints 0
It's different because &
will always evaluate both operands, whereas &&
won't look at the second operand if the first one is false
because the whole expression will always be false
no matter what the second operand is.

jlordo
- 37,490
- 6
- 58
- 83
2
&
will evaluate both the operands&&
will skip evaluation of the second operand if the first operand is false

Bakuriu
- 98,325
- 22
- 197
- 231

PermGenError
- 45,977
- 8
- 87
- 106
1
& is a bitwise 'and' operator, && is a boolean 'and'
& will always evaluate both the left and right sides, && will only evaluate the left if that is sufficient to evaluate the expression (e.g. false && true : only the LHS is evaluated because if the LHS is false, the whole expression must be false)

NickJ
- 9,380
- 9
- 51
- 74