Humanware
Humanware

Reputation: 3

Why does i += ++i result in 1 in Java?

I was learning Java. I am facing a problem with the following expression:

int i = 0;
i += ++i;
System.out.println(i);

It says the output is 1.

If we rewrite it like this:

i = i + ++i;

When increment happens, does it change the value in the address? If so, then i + ++i should be 2. And also does it differ in different languages?

Also this:

i = i + ++i + i;

Upvotes: -8

Views: 94

Answers (2)

Ankur
Ankur

Reputation: 11

See, You should learn how Increment/Decrement operators works actually, Both ++i and i++ increase the value of i by 1, but they work differently!!

Pre Increment(++i) : First, increments the value of i by 1 then, it uses the updated value in the expression

Example:

int i = 5;
int a = ++i;  // i is incremented first, then assigned to 'a'
System.out.println(a);  // Output: 6

**Post Increment(i++) : **First, uses the current value of i in the expression then, it increments i by 1

Example:

int i = 5;
int b = i++;  // i is assigned to 'b' first, then incremented
System.out.println(b);  // Output: 5
System.out.println(i);  // Output: 6 (because it was incremented after assignment)

Upvotes: 0

Amit Kadlag
Amit Kadlag

Reputation: 39

Lets Debug this step by step:

  1. int i = 0; → i is initialized to 0. so i contains the value 0

  2. ++i → Pre-increment happens, so nows i becomes 1.

  3. i + ++i → Substituting values:

  4. i is 0 (original value before pre-increment).

  5. ++i makes i = 1, so now ++i returns 1.

  6. i + ++i = 0 + 1 = 1.

  7. i = 1 (final value).

  8. System.out.println(i); prints 1.

Your Next question Does the increment change the memory address?

  • No, in Java, int is a primitive type, which means it is stored directly in memory, not as a reference. The value of i is updated in the same memory location. When you write ++i, it modifies the value in place.

Upvotes: 0

Related Questions