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 Beginning Java and the fly likes Doubtful answer 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 » Java » Beginning Java
Bookmark "Doubtful answer " Watch "Doubtful answer " New topic
Author

Doubtful answer

bettina akinsuyi
Greenhorn

Joined: Feb 03, 2007
Posts: 8
Dear comrades, i want someone to solve this. Please, good proof or explanation no room to question the message poster.



Given:

1. class Ifs {
2. public static void main(String [] args) {
3. boolean state = false;
4. int i = 1;
5. if((++i > 1) && (state = true))
6. i++;
7. if((++i > 3) || (state = false))
8. i++;
9. System.out.println(i);
10. }
11. }


What is the result?





A
3
B
4
C
5
D
Compilation fails.
E
An exception is thrown at runtime.

I think answer should be 4 because there is preincrement greater in line 7 and not 5 as the answer show in the book.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by bettina akinsuyi:
Dear comrades, i want someone to solve this. Please, good proof or explanation no room to question the message poster.



Given:

1. class Ifs {
2. public static void main(String [] args) {
3. boolean state = false;
4. int i = 1;
5. if((++i > 1) && (state = true))
6. i++;
7. if((++i > 3) || (state = false))
8. i++;
9. System.out.println(i);
10. }
11. }


What is the result?





A
3
B
4
C
5
D
Compilation fails.
E
An exception is thrown at runtime.

I think answer should be 4 because there is preincrement greater in line 7 and not 5 as the answer show in the book.


Notice that in line 5, the second condition in the && is an assignment statement.

The boolean is set to true, and the value of the assignment statement is true.

So ++i in the body of the loop is executed.
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
1. Carefully re look at your code. (state = true), not ==.
2. Run the code yourself, in a debugger if possible and walk through.


Let me know if this doesn't make sense. Good luck!
/Pete
[ March 22, 2007: Message edited by: pete stein ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubtful answer
 
Similar Threads
Game Tutorials -->> TicTacToe
Short-Circuit Logical Operators
3D array Figure
Why does count not reflect # of tokens?
Strange IF condition