File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ++ Operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "++ Operator" Watch "++ Operator" New topic

++ Operator

Alamu Vinai

Joined: Feb 01, 2001
Posts: 19
Why is the output to i = 2 in the following scenario? I applied the logic discussed by Maha, the value should be i = 0. Can any one explain this?
URL for maha's discussion:
public class add
public static void main(String args[])
int i =0, j =2;
i = ++i;
}while (j>0);
System.out.println("i value " + i);
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
The do while is going to execute 2 times, the first time through j=2(then 1) the second time through j=1(then 0) - and now the loop ends.
The first time through the loop the i = (bump to 1 first)1;
The second time through the loop the i = (bump to 2 first)2;

"JavaRanch, where the deer and the Certified play" - David O'Meara
natarajan meghanathan
Ranch Hand

Joined: Feb 01, 2001
Posts: 130
Hi, The loop is executed twice. Since it is a do-while it is executed once atleast. So after the first execution, j=1 (>0). So it is executed again. now j=0 (not >0). So control comes out of the loop. Each time the loop is executed, u r incrementing i once. So i=2 finally when u print outside the loop.

Sun Certified Programmer for Java 2 Platform
Ananda Kashyap

Joined: Jan 03, 2001
Posts: 23
If you put i = i++; instead of i = ++i; then only the answer will be 0, that was a earlier discussion.
- Ananda.
Alamu Vinai

Joined: Feb 01, 2001
Posts: 19
I think I should have explained it clearly.
I know the loop is executed two times.
As per Maha,
"Be careful when the assigned var is the same as the var which undergone all these ++/-- operations in the statement.
In this case the assigned var takes its latest value"
i = 0;
i = ++i;
The value is assigned to i again. As per the logic of Maha,
i = [1]0;
and i gets the latest value, which is 0 here.
The value of i should be 0. Not 2.
Also, in the above program, if you substitue the line
i = i++, the value of i after the loop is 0.
Can any one explain me this?
natarajan meghanathan
Ranch Hand

Joined: Feb 01, 2001
Posts: 130
Thats a beauty. I made a mistake in one of the mock tests.
ok. first i=0;
then i=i++; i is assigned 0 first, then incremented (but of no use). i on the LHS has been assigned 0.
This happens again for the second time. So u get i printed out to be 0.

Thanks for making me remember the catch.
I agree. Here's the link:
subject: ++ Operator
It's not a secret anymore!