+ 2
I think it's always better to use && instead of &. Are there any real life scenarios where & is more useful than && ?
If we're using &&, second part will not be evaluated if first part is false. Which are the scenarios where we need to check second part even if the first part is false?
2 ответов
+ 6
These are two different operators that you use for different tasks.
First, && is a logical AND operator, you use it to evaluate boolean expressions in if, else if statements, etc.
Second, & is a bitwise AND operator, you use it when you are working with binary numbers and need to change their bits.
Don't mix them up
+ 12
@Ashish Kulkarni is actually right
the & operator works in an if too, and like he said it evaluates the whole expression even if the first one is false
here is an example:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside");
}
System.out.println(x);
//output "1"
it's not used very often but there might be some sort of scenario when you need sth like my example
imagine a matchmaking system where you need to count the users even when they are not connected yet
if (user.connected & (users++ = maxUserAmount){
startgame ();
}