Possible Duplicate:
& vs && and | vs ||
What is the difference between &
and &&
?
I am getting same output for both &
and &&
.
Ex:
&&
:if (true && true){ System.out.println("------if------"); } else { System.out.println("------else------"); }
&
:if (true & true){ System.out.println("------if------"); } else { Sy开发者_如何学Cstem.out.println("------else------"); }
Output:
------if------
------if------
Can we use &
and &&
operators in our code interchangeably?
&&
short circuits the evaluation, while &
always evaluates both operands.
This is a duplicate question. I'll try to dig out the link for you...
- logical operators in java
&
will force the evaluation of both the left and right operands whereas &&
is the short-circuit operator and doesn't check the right operand in obvious cases.
// this will evaluate both method calls even if the result
// of checkSomething() is false
boolean result = checkSomething() & checkSomethingExpensive()
// this will skip evaluation of checkSomethingExpensive() if the result of
// checkSomething() is false
boolean result = checkSomething() && checkSomethingExpensive()
&
- bitwise AND&&
- logical AND
You've true in both cases because in case of logical AND reason is obvious and in case of bitwise AND - true is interpreted as 1, so 1 & 1
alsays returns 1
which turns out into logical true
logical AND &&
Java operators
The bitwise & operator performs a bitwise AND operation.
Java operators2
Rule of thumb : use && when dealing with booleans, conditions, ifs, etc. I.e. most of the time. Use & in the rare cases when you need to perform bits operations.
- &: operation, boolean true & true == true, integer 1001b & 1110b == 1000b
- &&: comparison, boolean true & true == true, integer compiler error
That's because the following is evaluated:
I will write it in english semantic for you to understand.
For output 1: Logical AND &&
if true AND true IS TRUE.
For ouptut 2: Bitwise AND &
- Let x = true (in other words, bit
1
) - x = x AND true (in other words,
x = 1 & 1
) Bit is AND'ed - if (x IS TRUE) then print the if statement.
&& is a comparison while & is an operation!
精彩评论