File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes i=i++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "i=i++" Watch "i=i++" New topic
Author

i=i++

huang daobin
Greenhorn

Joined: Aug 11, 2005
Posts: 2
can someone help me
code:
public class A {

public static void main(String arg[]) {
int i = 0;

i = i++;

System.out.println(i);

}
}
the output is 0,why?
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

The value contained in the 'i' variable is incremented. However, the expression 'i++' evaluates to the pre-increment (original) value of 'i'. The '=' assignment operator has the least precedence, so it happens last: the value of the expression 'i++' -- the original value of 'i' -- is assigned back to 'i'.

The moral? This is good to know for testing, but anyone who writes production code like this should be slapped with a mackerel.
[ August 11, 2005: Message edited by: Steve Morrow ]
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

The following might help you understand:
Hopefully you wouldn't expect a different value for 'j' than you would have for the left-hand 'i' from "i=i++".
Roopesh Gulecha
Ranch Hand

Joined: Aug 09, 2005
Posts: 32
Hello Steve,
Sorry but I got a little confused with your earlier explanation.
When we have
j = i++; (which means j = i and i = i + 1)
ofcourse j = 0 since i++ is post-increment; and then i++ becomes 1 due to post-increment.

But yet when we have
i = i++;
shouldn't the post-increment part 'i++' change/increase the value of i from 0 to 1 as it did in the last case.
Isn't this same as (i = i and i = i + 1)
Hope you can put some light on this.

Thanks,
Roopesh.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

But yet when we have
i = i++;
shouldn't the post-increment part 'i++' change/increase the value of i from 0 to 1 as it did in the last case.
Let's assume the original value of 'i' is 0. Think of the steps like this:

1) Evaluate the expression "i++" (the result is 0).
2) Increment that value of i ('i' is now 1).
3) Assign the value of the expression (obtained in #1, this value is 0) to the variable 'i' ('i' is now 0).

Remember that the assignment operator '=' is handled last, not the incrementation (is that a word? ).

This is the same sequence as with "i = j++", to wit (where j is 0):

1) Evaluate the expression "j++" (0).
2) Increment the value of j ('j' is now 1).
3) Assign the value of the expression to 'i' ('i' is now 0).

Hope this helps.
Radiya Sojitrawala
Greenhorn

Joined: Aug 06, 2005
Posts: 12
Hi,

I am confused too..

I expected this
i = i++;
=> i = (i++); // precedence of post increment over assignment
=> i = (0++); // replace i by 0
=> i = (0 + 1);
=> i = 1; // ???

please can someone explain why is this wrong?

TIA
Radiya
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

I am confused too..
I don't know how else to put it. The expression "i++" is evaluated to be the original value contained in 'i'. Whether or not 'i' is actually incremented or not is pretty much irrelevant. It's the result of the expression "i++" (the original value) that gets assigned back to 'i'.

The phrase "post-increment" means that the value is incremented after the expression is evaluated. Regardless, it's important to remember that it's the result of the expression that gets assigned to 'i'.

Again, let's go back to the "j = 0; i = j++" example. You don't (or shouldn't) expect the value of 'i' to be 1, as the value of the expression "j++" is 0. Similarly, "i = 0; i = i++" performs the same way. The result of the expression "i++", which is 0, gets assigned to 'i'.

Hope this helps!
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16


=> i = (0++); // replace i by 0


i think the misunderstanding comes around this line. we do NOT increment the value of the expression, we increment the variable.

in other words, when we have and expression with pre- and post-incrementing, the steps we follow are

1) do all pre-incrementing.
2) evaluate the expression, and SAVE IT SOMEWHERE TEMPORARILY
3) do all post-incrementing
4) (if needed) assign that TEMPORARILY SAVED VALUE to the variable on the left hand side.

so, you what we really get is this:

i = i++;
there are no pre-increments, so evaluate the expression as if there were no post-increments...
clearly, the RHS evaluates to 0. remember that.
now do the post increments. i becomes 1.
Finally, do the assignment. the expression evaluated to 0 (i remembered that), so assign o to i.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

That's certainly another way to put it! Thanks for the excellent explanation, fred.
Ryan Kade
Ranch Hand

Joined: Aug 16, 2005
Posts: 69
This is more or less what Fred said, but I thought I'd give a code-wise example. It's similar to this:



Or, to be a little less confusing by not using the same var name:



That's what's supposed to be happening under the hood.

[ August 16, 2005: Message edited by: Ryan Kade ]
[ August 16, 2005: Message edited by: Ryan Kade ]
John M Morrison
Greenhorn

Joined: Jul 25, 2005
Posts: 21
Ecch. Whatever y'all are doing don't do crap like

int j = k++;

Always do incrementation on its own line. Do not depend
on post and preincrement. It just becomes an obfuscatory
mess. I discourage my students from doing thing. Clarity
always is more important than any (perceived) optimization.

JMM
ambati prashanth
Greenhorn

Joined: Aug 07, 2005
Posts: 20
Originally posted by huang daobin:
can someone help me
code:
public class A {

public static void main(String arg[]) {
int i = 0;

i = i++;

System.out.println(i);

}
}
the output is 0,why?



hi please see my explanation,
the code is i=i++;
shall iwrite it as j=i++;
and i=j;
the above 2 statements are equal to the one you required.
now print individually
j=i++;
System.out.println("this is i"+i);
System.out.println("this is j"+j);
i=j;
System.out.println("this is j"+j);
System.out.println("this is i"+i);

now see the out puts of the variables in each and every place.

Regards
Prashanth.
nitin nagar
Greenhorn

Joined: Jun 30, 2005
Posts: 2
hi huang,
it's very simple in terms of language, problem is that it looks typical...
look it in following way..
when you wirte
i = i++;
it treated as an assignment statement, which has variable (i) on left hand side in which value of right hand side expression will be calculated and assigned.

now, we are using post increment here so before incrementing the 'i' it's value is stored in temp buffer (for expression use )which is zero.
then it is incremented by 1 so 'i' becomes 1.

now,
As expression is evaluated so assingment will be performed (which is always done at very last in any arithmatical statement)

and as a result it reassign 'i' to the value of expression from temp buffer which again makes 'i' to zero.

i hope you got it now.
Ashok George
Ranch Hand

Joined: Mar 25, 2005
Posts: 87
that was a real gud discusion that went around here..
i am new member to this forum but i really apreciate the spirt and the time and effort u ppl spent on it and i do wish and hope for more in the future all the best to every 1 .. hurray to java RANCH!!!
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

Ecch. Whatever y'all are doing don't do crap like

int j = k++;
Couldn't agree more, but this is the kind of "crap" that shows up repeatedly on mock exams, and it helps to have an understanding of what's going on here for purposes of the SCJP.

That said, anyone who writes something like that in production code ought to be flogged about the face and shoulders with a dead mackerel.
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
class abc{

public static void main(String... av){
int i=0;
int j=0;
j=i++;
System.out.println("i="+i);
System.out.println("j="+j);
System.out.println("i="+(i++));
System.out.println("i="+i);
}
}

prints:
i=1
j=0
i=1
i=2

I think the real intricacy of the question is when we do something like i=i++ what exactly is the order in which the statements are executed.
The above observation confirms my knowledge that the increment is done after the current statement is executed, but it doesn't make things easier when I try to evaluate i=i++
i(new)=i(old) and then what?
Sorry but I can't really get this into my head!


"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill
anand phulwani
Ranch Hand

Joined: Sep 10, 2005
Posts: 242
This is How should i conclude this topic

i=1;
when i=i++; happens what goes behind the scenes,

= is always of higher precedence than ++,-- in this case
so when we execute

i=i++;

The compiler know that i should get the value 1 after completing this statement whether i is ++ or i is --,So We can Say that whenever
such statement in which the same variable is assigned its postfix addition ++,-- are ignored.
[ September 16, 2005: Message edited by: anand phulwani ]

Thanks and Regards, Anand
SCJP 5.0 310-055 73%, SCWCD 1.4 310-081 78%, IBM DB2 9 Fundamentals 000-730 62%
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Hi anand,


This is How should i conclude this topic

i=1;
when i=i++; happens what goes behind the scenes,

= is always of higher precedence than ++,--
so when we execute

i=i++;


I am afraid you are wrong.
Please refer to the chapter 2 of Sybex Complete java 2 certification to know the operator precedence

TABLE 2 . 1
Operators in Java, in Descending Order of Precedence
Category Operators
Unary
++ -- + - ! ~
(type)
Arithmetic
* / %
+ -
Shift
<< >> >>>
Comparison
< <= > >= instanceof
== !=
Bitwise
& ^ |
Short-circuit
&& ||
Conditional
?:
Assignment
=
op=


= operator has the least precedence.

I request you to please reconsider your post and edit it, so that other members dont get misleaded by your post.

Sandy


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
I think this statement could be explained as follows:
k = i++;
ok so we know that ++ has the highest precedence ..right.
so we think that first i would be incremented to 1 and since = has the least precedence, the new value of i would be assigned to i.

but actuall compile does not works same.
1) It just stores the current value of i in buffer for later assignment in case of POSTFIX increment of decrement,
2) It increments the value of i.(the value in buffer remains same).
3) It assigns the buffered value of i to the variable k.

so you cannot say that in this case = has priority than ++; instead it still works according to its precedence order.

hope this would help Mr. Anand.

Sandy
anand phulwani
Ranch Hand

Joined: Sep 10, 2005
Posts: 242
Dear Mr Sandeep,

I would Really appreciate if you could tell me
where this logic is given because i tried
searching Sybex and i was not able to find
in it.

Thanks For Correcting Me,
With Regds,
Anand
anand phulwani
Ranch Hand

Joined: Sep 10, 2005
Posts: 242
i think we should not do duplicate posting....
continuing the same topic in a new thread

Is assignment precedence(=) higher than postfix unary assignment(var++)

Mr Sandeep is reuested to post on the same
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
I repeat, there is no problem with k=i++
the problem is with i=i++
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Akshay why dont you apply the same thing with
i=i++;

as i have told in my previous post, how does the compiler seems to work in such cases.

Just try to be a compiler for some time and do as it would have evaluated the statement.

I am sure you will get your answer.

(Hint: take the value of i in buffer, increment i (not buffer), assign buffered value to i again);

Hope this will help you.

Sandy
[ September 16, 2005: Message edited by: Sandeep Chhabra ]
Arun kumar
Greenhorn

Joined: Sep 17, 2005
Posts: 19
hi all,
i'm a new joinee to this group which is really interactive and lively. i just want to put some light on this contention from my perspective. please dont slap me with mackerel if i'm wrong rather just justify, i'll admit that. anyway here goes my point....

i think if we concentrate more on the precedence of operators then we can understand the scene better. surely i'm retelling the same story but it may help someone.

the experssion tells JVM that the value of i++(which is 0) should be assigned to 'i'(so, it has been determined that at the end of the expression the value of i is gonna be 0 only) but since the '=' operator is of least precedence this activity will be done as the last activity of i=i++; expression(so, this is a pending activity). now the second activity is to incerement the value of i to make it 1 from 0. after this there is no other work remains except the pending activity. so the JVM performs that pendind activity and assigns back the 0 to i, so for the time being the value of i was 1 but again it became 0.

Arun Kumar
in theory, theory and practice are same, but in practice they are not....
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Hi Arooon,

Welcome to the group. And your point is just fine...Why to worry...

Cheers !!

Sandy
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
ok let me do as you say
you say that assignment has lowere precedence than the increment op right?

int i=0;
i=i++;
// first put i(old) into a temp: temp=i(old)
// then increment i: i(new)=i(old)+1 => i(new)=1
// then do the assignment: i(newest)= temp => i(newest)=0 again.

Ah! that works, thanks a big deal, i just needed to know the exact implementation
saxena vicky
Greenhorn

Joined: Sep 05, 2005
Posts: 18
Hi all,
Can anyone explain me:
1. int i= 0;
i=i++ + ++i + ++i;
System.out.println(i);
OUTPUT IS: 5

2. int i= 0;
i=i++ + ++i + --i;
System.out.println(i);
OUTPUT IS: 3
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
Hi,


Hi all,
Can anyone explain me:
1. int i= 0;
i=i++ + ++i + ++i;
System.out.println(i);
OUTPUT IS: 5

2. int i= 0;
i=i++ + ++i + --i;
System.out.println(i);
OUTPUT IS: 3



Let consider the first code..

int i= 0;

i=i++ + ++i + ++i;

Here i++ + ++i + ++i is the expression and

i++ is a post increment which means the value used in an expression is the original value of the variable and only later the variable gets incremented


Ex: Ex:j=i++ +5 + i++;
//here i value used in the calculation is 0 in the first place and in the second part it becomes 1..
j=0+5+1...


So..i++ + ++i + ++i

0(0++ = 1 This is post increment so original value is used in expression) + 2(++1 pre increment is 2) + 3(++2 pre increment is 2)


So i= 0 + 2 + 3
i=5.


Now let us take the second code:

i=i++ + ++i + --i;

Considering the earlier sceanrio...

i++ + ++i + --i is

0 (0++ = 1 This is post increment so original value is used in expression)
+ 2(++1 pre increment is 2) + 1(--2 pre decrement is 1)


So i= 0 + 2 + 1
i=3.


Hope You got it...



[ October 10, 2005: Message edited by: A Kumar ]
[ October 10, 2005: Message edited by: A Kumar ]
saxena vicky
Greenhorn

Joined: Sep 05, 2005
Posts: 18
Thanks Kumar,
I got it..............
Dennis
Greenhorn

Joined: Oct 04, 2005
Posts: 6
here is some useful example for u.

you got '0' after executing b coz yr coding is post increment that is
b=0
a=b++;// that is assign value b to a before increment.
now a==0,b==1;

a=++b;// that is assign value b to a after increment.
so now, a==1 and b==1;


NOTE : the unary operation is perform on binary.
that is b++; is operation on binary
and b=b+1; is operation on integer.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

here is some useful example for u.
The problem is that the example isn't quite accurate. In both cases, the assignment happens *after* the increment. The terms pre- and post-increment do not refer to any assignment, but rather whether the increment happens before or after the expression "i++" is evaluated. With pre-increment, the value is incremented before the expression is evaluated. With the postfix increment operator, the value is incremented after the expression is evaluated; i.e., per the JLS, the value of the postfix increment expression is the value of the variable before the new value is stored.

In the example, the assignment operator is evaluated *last* due to rules of precedence.

Hope this helps.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

NOTE : the unary operation is perform on binary.
that is b++; is operation on binary
and b=b+1; is operation on integer.

P.S. This indicates a misunderstanding as well; there is no distinction between "binary" and "integer" with respect to the operators. Perhaps you meant to say that "++" is a unary operator and "+" is a binary operator, but that pertains to the number of operands, not the data types on which they operate.

Regards...
John M Morrison
Greenhorn

Joined: Jul 25, 2005
Posts: 21
At the risk of repeating myself, I shall repeat myself. Hooey like

int i = 0;
i = i++;

will get you in trouble. For the nonsqueamish, here's the deconstruction

You declare i and set it equal to zero.
On the next line, i is evaluated and it is found to be zero (on the right)
Then i is incremented to 1.
Then the zero from the evaluation is passed back to i on the left-hand
side of the assignment.

Stuff like this is syntacticaly nightmarish. Don't do it.
Either you want to increment i, in which case you can do

i++;

on a line by itself. OR you want to temporarily increment i,
use it and then revert back. in this case:

i++;
//do whatever you want with i
i--;

By doing the increment on its own line, it is clear to the other
coder reading your program what you intend to do. Remember the
three magic words:

SIMPLICITY, CLARITY, GENERALITY.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19073
    
  40

John,

Please don't wake the zombies.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: i=i++