Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubtful answer

 
bettina akinsuyi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic