Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java increment and assignment operator [duplicate]

I am confused about the post ++ and pre ++ operator , for example in the following code

int x = 10;
x = x++;

sysout(x);

will print 10 ?

It prints 10,but I expected it should print 11

but when I do

x = ++x; instead of x = x++;

it will print eleven as I expected , so why does x = x++; doesn't change the the value of x ?

like image 787
user3803547 Avatar asked Jul 03 '14 23:07

user3803547


People also ask

What is I++ in JavaScript?

The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way. Follow this answer to receive ...

What is += addition assignment operator in Java?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.

Can you increment by 2 in Java?

There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in that they can be written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix increment/decrement. The meaning is different in each case.

How to increment var in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.


1 Answers

No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x and post-increment x++ compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.

Here is the sequence of events that leads to what you see:

  • x is assigned 10
  • Because of ++ in post-increment position, the current value of x (i.e. 10) is stored for later use
  • New value of 11 is stored into x
  • The temporary value of 10 is stored back into x, writing right over 11 that has been stored there.
like image 134
Sergey Kalinichenko Avatar answered Sep 20 '22 15:09

Sergey Kalinichenko