• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

++ Operator

 
Alamu Vinai
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://www.javaranch.com/ubb/Forum24/HTML/000775.html
public class add
{
public static void main(String args[])
{
int i =0, j =2;
do
{
i = ++i;
j--;
}while (j>0);
System.out.println("i value " + i);
}
}
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
natarajan meghanathan
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ananda Kashyap
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you put i = i++; instead of i = ++i; then only the answer will be 0, that was a earlier discussion.
- Ananda.
 
Alamu Vinai
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats a beauty. I made a mistake in one of the mock tests.
i=i++;
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic