Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java operator ++ problem

Tags:

java

operators

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 ?

like image 888
shanky Avatar asked Aug 04 '11 17:08

shanky


People also ask

What operator is == in Java?

== operator is a type of Relational Operator in Java used to check for relations of equality.

What is && and || in Java?

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

What is the use of += operator in Java?

Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.


1 Answers

Remember this, Java evaluates your expressions right to left (just like C and C++),

So if your code reads

z = z++

then if z is 0 before this line is executed, what happens is:

  1. z++ is evaluated as an expression, returning the value 0
  2. Then z is incremented because of the ++ operator, and it has the value 1.
  3. Now the z on the left is assigned a value z = (value returned by z++)
  4. Since the value returned by z++ was 0, z is reset to 0.

The important thing to note is that the result of the assignment inherent in z++ is evaluated before the z variable on the left is updated.

like image 142
Rajesh J Advani Avatar answered Oct 21 '22 05:10

Rajesh J Advani