Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the increment operator behave in Java?

Tags:

java

Why is the result 8 and not 9?

By my logic:

  1. ++x gives 4
  2. 4 + 4 gives 8, so x = 8
  3. But after that statement x should be increased due to x++, so it should be 9.

What's wrong with my logic?:

int x = 3;
x = x++ + ++x;
System.out.println(x); // Result: 8 
like image 597
Adam Ary Avatar asked Nov 03 '15 08:11

Adam Ary


People also ask

How does increment operator work in Java?

Increment in java is performed in two ways, 1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.

How does increment operator work?

In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable.

Is += the same as ++ in Java?

scoreTeamB++ returns the previous value of the variable (before it was incremented). += returns the value that was assigned to the variable.

What is ++ A and A ++ in Java?

a++ vs. Popular languages, like C, C++ and Java, have increment ++ and decrement -- operators that allow you to increment and decrement variable values. To increment a value, you can do a++ (post-increment) or ++a (pre-increment): int a = 1; a++; printf("%d", a); // prints 2.


2 Answers

You should note that the expression is evaluated from the left to the right :

First x++ increments x but returns the previous value of 3.

Then ++x increments x and returns the new value of 5 (after two increments).

x = x++ + ++x;
    3   +  5     = 8

However, even if you changed the expression to

x = ++x + x++;

you would still get 8

x = ++x + x++
     4  +  4   = 8

This time, the second increment of x (x++) is overwritten once the result of the addition is assigned to x.

like image 99
Eran Avatar answered Oct 12 '22 06:10

Eran


++x is called preincrement and x++ is called postincrement. x++ gives the previous value and ++x gives the new value.

like image 20
Burak Keceli Avatar answered Oct 12 '22 06:10

Burak Keceli