Reputation: 59690
Is following true in java:
In java if you use ||
then after getting first true condition it neglects the rest conditions. That is If you write if(a || b || c)
in java and java finds a
is true then it will not check for b
and c
, just go into the if case.
Upvotes: 2
Views: 164
Reputation: 9690
Yes, and one important thing, if you do any operations in the second part, they will not be made. For example:
int a = 5;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 5
//b = 5
BUT in case:
int a = 3;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 4
//b = 5
I tried to make a simple example, but sometimes you call a method in the second part, (which will not be called if first part was true
in case of ||
), or the first part was false
in case of &&
Upvotes: 0
Reputation: 477464
That's correct, and that's not just laziness on part of the language implementation, but rather it is a crucial feature - short-circuiting allows you to write something like this:
if (myarray.length > 10 && myarray[10] == 5) { /* ... */ }
Here the second condition may only even be evaluated if the first one is true. Thanks to short-circuiting, if the first condition is false the second is never touched.
Upvotes: 1
Reputation: 1957
Yes it is correct. If you use | this operator to check OR condition then it checks rest all conditions. It also applied on AND(&) operator.
Upvotes: 0
Reputation: 5502
Yes, This way the compiler avoids unnecessary checking and calculation overhead.
Upvotes: 1
Reputation: 11184
Yes this is called short circuiting, if you put less expensive checks to the left you might avoid the expensive ones to follow.
This works for ||
and &&
one of the best uses is checking a value from an object that might be null:
if(myList != null && myList.size() > 6)
the previous line is null safe, reversing the condition will cause a null pointer exception in case myList is null
Upvotes: 3
Reputation: 24759
Yes, it's called short-circuiting. It also will short circuit &&
, i.e.
if (a && b && c)
If a
is false
then the condition cannot be true, neither b
nor c
are checked.
This can be problematic if you call methods that return booleans. To get around this, you can use bitwise &
and |
.
Upvotes: 0
Reputation: 726939
This is correct. ||
is called short-circuit OR
evaluation, or an OR-ELSE operator.
This is important in situations when evaluating the right-hand side may cause an undesirable consequence:
if (myString == null || myString.indexOf("hello") != -1)
...
would crash if it were not for short-circuiting.
Upvotes: 2
Reputation: 59690
(AFAIK)
The same things applies to &&
but in reverse manner.(for first false).
The same rule as in circuits for AND and OR gates.
Upvotes: 0