+ 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???

3rd Jul 2019, 3:14 AM
Jyoti Prakash
Jyoti Prakash - avatar
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
3rd Jul 2019, 5:55 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Because x is incremented and stored as 35, after that y is stored with the value of x
3rd Jul 2019, 3:23 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
0
x 34 x 35 y 35
3rd Jul 2019, 7:43 PM
zemiak