简体   繁体   中英

what will be the reason behind the output of java code?

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?

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.

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.

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM