This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "confusing x++, help!" Watch "confusing x++, help!" New topic

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;

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 ?

Andrew Edmonds

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

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:
subject: confusing x++, help!
It's not a secret anymore!