• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubtful answer

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic