2

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.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207

8 Answers8

3

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

MahdeTo
  • 11,034
  • 2
  • 27
  • 28
2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Yes, This way the compiler avoids unnecessary checking and calculation overhead.

me_digvijay
  • 5,374
  • 9
  • 46
  • 83
1

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

YES

(AFAIK) The same things applies to && but in reverse manner.(for first false).


The same rule as in circuits for AND and OR gates.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
0

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 |.

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
0

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.

Abhendra Singh
  • 1,959
  • 4
  • 26
  • 46
0

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 &&

mohdajami
  • 9,604
  • 3
  • 32
  • 53