This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "fall - through for if-else loop ???" Watch "fall - through for if-else loop ???" New topic
Author

fall - through for if-else loop ???

Mehul Mehta
Greenhorn

Joined: Aug 22, 2006
Posts: 7
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

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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: fall - through for if-else loop ???
 
Similar Threads
q from sun's epractice exam
IS if (b ) same as: if (b == true) ???
If condition
assigning boolean to integer.
Boolean Question