Alex Rivera | Logout

java operator ++ problem

Asked 2011-08-04T17:15:16.007
10

I wonder why first code output is 000 while the second one is 123

first one:

int z=0;
    while(z<4)
    {
       z=z++;
       System.out.print(z);

    }

second one :

int z=0;
int x=0;
    while(z<5)
    {
       x=z++;
       System.out.print(x);

    }

what is the different between these two codes , why the first block do not increase the value of the z ?

Edit
Report

2 Answers

4

When you use the post-increment operator, you don't need to assign the result back to the variable.

That is, your code should look like this:

int z=0;
    while(z<4)
    {
       ++z;
       System.out.print(z);

    }

In Java, the operation returns the value of z BEFORE the increment (while incrementing the variable behind the scenes afterwards), and that value is then RE-assigned to z. That's why it never changes.

The pre-increment operator will do the increment and return the NEW result, so you'll get what you expect:

int z=0;
    while(z<4)
    {
       z=++z;
       System.out.print(z);

    }

This will print 1234.

answered 2011-08-04T17:19:54.150
1

It's because you are assigning the value of z with a postfix operator.

http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

int z = 0;
i = z++; // i equals 0
x = ++z; // x equals 2

Postfix operators will increment the value of z after assignment of i.

Unary operator ++ will increment the value of z before assignment of x.

Think of it as ++ before z as +1 before assignment, ++ after z as +1 after assignment.

answered 2011-08-04T17:19:51.733

Your Answer