wood burning stoves 2.0*
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
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 ]
 
wood burning stoves
 
subject: Doubtful answer