aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes confusing x++, help! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "confusing x++, help!" Watch "confusing x++, help!" New topic
Author

confusing x++, help!

sarim raza
Ranch Hand

Joined: Nov 02, 2000
Posts: 232
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

Joined: Nov 05, 2000
Posts: 7
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

Joined: Oct 06, 2000
Posts: 25
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
 
subject: confusing x++, help!