• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confusing x++, help!

 
sarim raza
Ranch Hand
Posts: 232
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone account for the output of the following?
public class Sarim {
int x = 0;
while(x++<2);
System.out.println("Hi");
}

How many times will Hi be printed out and why ?
assuming y=x, how do the values of x and y change at each iteration of the while loop?
how about if we use ++x instead ?
thanks

 
Andrew Edmonds
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would expect Hi to be printed twice. This is because x++ will only increment after the expression has been resolved. So the first time x =0, the second it will be 1.
Using ++x means that x will be incremented first before the expression is resolved. So, x's first value would be 1. Hence Hi should be printed once.
I haven't run this myself but this is the output I would expect.
 
greg clarke
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tricky question Sarim, or just a trick question maybe.
The code doesn't compile, since there is no method. I've put your statements inside a main method and run the code. "Hi" is printed just once, which may surprise if you don't notice the semi-colon at the end of the while statement.
If you take away the semi-colon then Andrew is right for x++ and ++x.
I wonder if there will be anything like this in the exam.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic