Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

fall - through for if-else loop ???

 
Mehul Mehta
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code:
class Bool {
static boolean b;
public static void main(String [] args) {
int x=0;
if (b ) {
x=1;
}

else if (b = false) {
x=2;
}
else if (b) {
x=3;
}
else {
x=4;
}
System.out.println("x = " + x);
}
}
ANSWER is X=4;

It appears that there is fall-thru......does if -else also have fall-thru or only case switch ???
 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It appears that there is fall-thru


I do not see how a "fall-through" is observed. Just traverse through the code keeping in mind how the if-else works.

b is initialised to false by default.

x = 1 is not executed since if(false) is encountered.

b is assigned false, else if(false) is encountered.

else if(false), x is not assigned 3

Here x is assigned 4.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"fall-through" is unique to the switch statement. x is 4 here because all of the tests in the "if" statements are false, so the last "else" executes. Why do you think this implies "fall-through?"
 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no fall through in the above code. You simply use your basic if else concept and you will get the correct answer.
 
Mehul Mehta
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is from the Whizlabs Software and the reference explanation says "fall-thru"; i guess they are wrong there.

I was pretty sure that if-else does not use "fall-thru" since I must have used a billion times ; I decided to put this on the forum for :-
1) Whiz lab Explanation.

2) I was guessing the part "else if (b = false)" would evaluate to TRUE and satisfy the clause and hence X=2;
because we are assigning FALSE to 'b' and not checking.


Thanks for the explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic