1

Consider the following simple java code

public static void main(string args[])
{
  int x=10;
  int y;

  y=x++;
  y=y--;

  System.out.println(y);
}

here output is 10. but actually y variable decrements. but according to me output should be 9. what is the reason?

Barmar
  • 741,623
  • 53
  • 500
  • 612

5 Answers5

3

The postfix-increment operator works as follows:

  • Increment the operand
  • Return the previous value of the operand

The postfix-decrement operator works as follows:

  • Decrement the operand
  • Return the previous value of the operand

Therefore, the following piece of code works as follows:

x = 10;  // x == 10
y = x++; // x == 11, y == 10
y = y--; // y ==  9, y == 10

As you can see, y = y-- is equivalent to y = y.

It has no effect on the value of y at the end of the operation.

barak manos
  • 29,648
  • 10
  • 62
  • 114
1

You need to understand about prefix and postfix operators.

y=x++ means assign x to y and then increment x by 1;

y=++x means increment x and then assign the incremented value to y.

If you understand this difference then its obvious what the code does.

Nazgul
  • 1,892
  • 1
  • 11
  • 15
  • I don't know how this answer is different from above answer so it got 2 votes up! +1 –  Aug 23 '14 at 10:22
  • I don't think what you stated is equivalent to barak's answer. Your answer implies that the decrement occurs after the assignment. According to your statement, `y=y--` is equivalent to `y=y; y=y-1;` which is not the same as what the other answers are saying... – Tung Aug 23 '14 at 10:30
  • explaining something to a beginner in sample code is often confusing as against explaining the same thing in plain English. – Nazgul Aug 23 '14 at 12:12
0

The post-decrement operator returns the old value of the variable. So when you write

y = y--;

it decrements y, then assigns the old value back to y. It's as if you wrote:

old_y = y; // Save old value
y = y - 1; // perform y-- decrement
y = old_y; // Assign the saved value
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Here's whats happening

int x=10; 

declare a vaiable x and assign 10 to it.

int y;

declare a variable y

y=x++;

increment x therefore x=11 and return its old value therefore y=10

y=y--;

decrement y therefore y=9 at current point, and return its old value which is 10 and is caught by y therefore y=10 now.

System.out.println(y);

Output

10
Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
0

x = 10; // x == 10

y = x++; //Here First Y is asigned with value 10 and increments x by 1

y = y--;//Here First Y is asigned with value 10 and decrements y by 1

Because If we use Postincrement or postdecrement First it asigns value to Variable then it performs increment or decrement .