• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Doubtful answer

 
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.
 
Ranch Hand
Posts: 2410
  • 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.
 
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 ]
 
I once met a man from Nantucket. He had a tiny ad
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic