Am confused at this PostFix Operator code, pls help.
Hi all,
pls chk this piece of code:
public class Program {
public static void main(String[] args) {
int i = 0;
for (int j = 0; j != 10; j++) {
i = i++;
}
System.out.println(i);
}
Its output is 0, can someone pls give a detailed explanation.
Thanx in advance.
> pls chk this piece of code:Not again.
http://onesearch.sun.com/search/onesearch/index.jsp?qt=increment+operator&col=developer-forums&subCat=&site=dev&dftab=&chooseCat=javaall&cs=false&rt=true
You increment i, and then assign the value to it that i had before it was incremented.
i = 0;
temp = i;
i ++;
i = temp;
i will still be 0. Don't do that.
Type in "i=i++" in the little Search Forums box on the left side of this page and see what the reason behind this all is.kind regards,Jos
JosAHa at 2007-7-14 22:24:26 >

> Type in "i=i++" in the little Search Forums box on
> the left side of this
> page and see what the reason behind this all is.
To be honest, all you'll be able to see is how the search fails for this conglomerate of special chars. If you omit the quotes, that is. :)
> > pls chk this piece of code:> > Not again.It will never end :(
kajbja at 2007-7-14 22:24:26 >

The postfix operator does it's own assignment. What, say, i++ is increment i, but return the previous value. You'd normally use it as something like:
int idx = 0;
int[] array = new int[10];
for(......) {
...
array[idx++] = v;
..
This assigns v to the next slot in the array.
If you do i = i++ nothing happens. Lets say i = 1 before.
The i++ increments i to 2 but returns the old value of i .e. 1 it then assigns this 1 back to i.
> > Type in "i=i++" in the little Search Forums box onthe left side of this
> > page and see what the reason behind this all is.
>
> To be honest, all you'll be able to see is how the search fails for this
> conglomerate of special chars. If you omit the quotes, that is. :)
I used the double quotes to indicate a literal value, isn't that the usual
way to express that in ordinary writing?
kind regards,
Jos (huh?)
JosAHa at 2007-7-14 22:24:26 >

> I used the double quotes to indicate a literal value,
> isn't that the usual
> way to express that in ordinary writing?
http://onesearch.sun.com/search/onesearch/index.jsp?qt=i+%3D+i%2B%2B%3B&subCat=siteforumid%3Ajava31&site=dev&dftab=siteforumid%3Ajava31&chooseCat=javaall&col=developer-forums
> > I used the double quotes to indicate a literal value,
> > isn't that the usual way to express that in ordinary writing?
>
> http://onesearch.sun.com/search/onesearch/index.jsp?qt
> =i+%3D+i%2B%2B%3B&subCat=siteforumid%3Ajava31&site=dev
> &dftab=siteforumid%3Ajava31&chooseCat=javaall&col=deve
> loper-forums
This is surreal ;-)
kind regards,
Jos
JosAHa at 2007-7-14 22:24:26 >

Many thanx to all.Apologies for posting this query before searching it in the threads.