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);
}
}
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);
}
}
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".
> > 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
> 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)
~