Confusion with unary operator : ++

Following code is producing z = 0 as a result.

Can any buddy justify this ...?

class A

{

publicstaticvoid main(String[] arg)

{

int z=0;

for(int k=0;k<10;k++)

z=z++;

System.out.println("z = " + z);

}

}

[639 byte] By [Vish_Vishala] at [2007-11-26 19:39:58]
# 1
z=z++;Never ever do that.It should be z++;Kaj
kajbja at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 2

Replace the line "z = z++" with just "z++" and see what happens.

The "++" operator is an assignment operator - i.e. when you write "z++", the value of z in is increaced by 1. You've already done this for k: The statement "k++" is not the same as just writing "k + 1" - it's the same as writing "k = k + 1".

Drossa at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 3
z = z++;is equivalent totemp = z;z = z + 1;z = temp;
CeciNEstPasUnProgrammeura at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 4
> z = z++;> > is equivalent to> > temp = z;> z = z + 1;> z = temp;After reducing, it's equivalent to:z = z; :o)~
yawmarka at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 5

> > z = z++;

> >

> > is equivalent to

> >

> > temp = z;

> > z = z + 1;

> > z = temp;

>

> After reducing, it's equivalent to:z =

> z;

:o)

>

> ~

Too extravagent, try

z

ScarletPimpernela at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 6
> Too extravagent, try > > zDoesn't compile ;)
kajbja at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 7
> > Too extravagent, try > > > > z> > Doesn't compile ;)Neither should z = z++;, but it does. ;-)
masijade.a at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 8

> Too extravagent, try

>

> z

Better yet...

int z=0;

for(int k=0; k<10; k++) ; // mmph...

System.out.println("z = " + z);

Further refactoring...

System.out.println("z = 0");

:o)

~

yawmarka at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...
# 9
> > Too extravagent, try > > > > z> > Doesn't compile ;)Ahh you must have one of those cheap compilers.
ScarletPimpernela at 2007-7-9 22:19:31 > top of Java-index,Java Essentials,Java Programming...