I have a question about IF
clause in Java . I have and expression:
if ((someObject != null & connectedToTheInternet) || operate) {
// some action
}
Is my logic right: if someObject != null
equals to true and connectedToTheInternet
equals false then we have (someObject != null & connectedToTheInternet)
equals false and then we have the following block:
if (false || operate) {
// some action
}
And if operate
equals true then // some action
will be triggered?
Just a first note: logical AND operator is "&&" and not just "&" (bitwise AND).
Following, your answer is YES... JVM will run conditions following your thinking.
By the way, I suggest you to read something abot short-circuit of these operators: it can be interesting if you are learning.
For example if you have if (a && (b || c)
and a==false
, then JVM won't evaluate b
or c
conditions because false && ...
will be always false.
The same in the case of if (a || b || c && d)
: if a==true
then JVM will ignore the other parts and consider it as true because true || ....
true || ....
will be always true.
Yes. if-clauses are evaluated from left to right. If no parenthesis are used, &&
has precedence, even higher precedence has !
(not) - similar to multiplication (AND), addition (OR) and negative numbers (-) in math (eg "A && (B || C) != A && B || C == (A && B) ||C") - I recommend to use parenthesis if you are unsure. This makes it possible to combine != null
checks and calls to methods in the same if statement (eg, if (object!=null && object.dosomething())
).
Btw. there is a difference between &
and &&
( short-circuit ), when &
is used, the second condition gets evaluated even if the first is false
already. When &&
is used, Java doesn't check the second condition if the first one is false
as the whole term cannot be true anymore - this is only important when the second condition is not a boolean variable but a method (which gets called or not -> side effects ; this "skipping" is called short-circuit). Same for ||
and |
where the second operator might not get evaluated if the first is already true
(in case of ||
).
Normally only ||
and &&
are used.
Just for completeness: &
is also the bitwise AND operator in Java.
if (false || operate) {
// some action
}
If operate true then if block executing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.