Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Boolean Question

Dave Fishburn
Greenhorn
Posts: 3
Hi all,
I'm a long time lurker here, gleening information about the Programmer certification and anything else that I've had a problem with. But this would be my first official post.
I ran accross this question in Suns ePractice test section and I'm having a hard time with one of the steps;
} class Bool {
static boolean b;
3. public static void main(String [] args) {
4. int x=0;
5. if (b ) {
6. x=1;
7. }
8. else if (b = false) {
9. x=2;
10. }
11. else if (b) {
12. x=3;
13. }
14. else {
15. x=4;
16. }
17. System.out.println("x = " + x);
18. }
19. }
The anxswer is x = 4
I cant see where the code fails to the else. I know b was initially defaulted to False and at line 8 it was rei-initialized to False. But I cnat determine how it falls to the else statement and sets x = 4.
Any help?
BTW, thanks for the great pointers over the last several months everyone. Im talking the test Jan 12th and you've all been a great help!

Dave Fishburn
Greenhorn
Posts: 3
Nevermind.
I see it now. b was set to false and by default fell out of the if statement.

Ko Ko Naing
Ranch Hand
Posts: 3178
Originally posted by Dave Fishburn:
Nevermind.
I see it now. b was set to false and by default fell out of the if statement.

Welcome to the Ranch!!!
It's good that u could find out the solution by urself....
In the case of b = false, b is assigned to be false and the condition got wrong. So it jumped down to the next condition and the thing happens in the last condition...
Hope to see u wondering around the ranch for long....

Surasak Leenapongpanit
Ranch Hand
Posts: 341

In line 2 default boolean b is false,
line 6 is not accessed,
line 8 b is assigned to false,
line 9 and 12 is not accessed,
the last else in line 14 sees b is true,and therefore x = 4.