Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if the first condition fails then the second condition will be examine -java [duplicate]

if i have a while condition in java as follows while(j>=1 && i<=7) my question is if the first condition fails then the second condition will be examine?? in other word if j=0 the compiler will check if I<=7 or it will ignore it . please help me thank you

like image 950
nana Avatar asked Jan 29 '26 16:01

nana


2 Answers

No, if the first condition returns false then the whole expression automatically returns false.

Java will not bother examining the other condition.

like image 169
Matias Cicero Avatar answered Jan 31 '26 05:01

Matias Cicero


(j>=1 && i<=7 && cond1 && cond2 && ... && condN) // will evaluate until the one condition fails
(j>=1  & i<=7  & cond1  & cond2  & ...  & condN) // will evaluate all the conditions

and with or

(j>=1 || i<=7 || cond1 || cond2 || ... || condN) // will evaluate until the one condition is true
(j>=1  | i<=7  | cond1  | cond2  | ...  | condN) // will evaluate all conditions

example:

lets use this 2 methods:

public boolean isTrue(){
  System.out.println("true");
  return true;
}

public boolean isFalse(){
  System.out.println("false");
  return false;
}

so, in the first case:

boolean cond = isFalse() && isTrue(); 

output is:

 false

value of cond is false

and in the second case:

boolean cond = isFalse() & isTrue(); 

output is:

 false
 true

value of cond is false

like image 32
Dima Avatar answered Jan 31 '26 07:01

Dima