+ 1
Increment in JAVA
public class Program { public static void main(String[] args) { int x = 34; int y = ++x; System.out.println(x); } } // if println x or y both gives same result 35 WHY???
3 Answers
+ 1
The ++ operator changes the value of x. To understand, compare these:
y = x + 1; // x remains 34, y is 35
y = x++; // first y gets the current value of x (34) then x is incremented to 35
y = ++x; // first x is incremented to 35, then y gets the value 35
+ 4
Because x is incremented and stored as 35, after that y is stored with the value of x
0
x 34
x 35
y 35