It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes fall - through for if-else loop ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "fall - through for if-else loop ???" Watch "fall - through for if-else loop ???" New topic

fall - through for if-else loop ???

Mehul Mehta

Joined: Aug 22, 2006
Posts: 7
class Bool {
static boolean b;
public static void main(String [] args) {
int x=0;
if (b ) {

else if (b = false) {
else if (b) {
else {
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

Joined: May 02, 2006
Posts: 218
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.

SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

"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?"

[Jess in Action][AskingGoodQuestions]
Sanjit Kumar
Ranch Hand

Joined: Dec 04, 2006
Posts: 35
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

Joined: Aug 22, 2006
Posts: 7
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.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: fall - through for if-else loop ???
It's not a secret anymore!