Reputation: 3
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
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
Reputation: 39
Lets Debug this step by step:
int i = 0;
→ i is initialized to 0. so i contains the value 0
++i
→ Pre-increment happens, so nows i becomes 1.
i + ++i
→ Substituting values:
i is 0
(original value before pre-increment).
++i makes i = 1
, so now ++i returns 1.
i + ++i = 0 + 1 = 1.
i = 1 (final value).
System.out.println(i); prints 1.
Your Next question Does the increment change the memory address?
Upvotes: 0