+ 2

Having problem with increment in Java

Can anyone please explain me why all of they are showing 35? I thought about 34, 34, 36. if I remove int z then x show 34. int x = 34; int y = x++; int z = ++y; System.out.println(x); System.out.println(y); System.out.println(z); //////// Output //////// 35 35 35

26th Feb 2018, 8:12 PM
Shariat Ullah Milon
Shariat Ullah Milon - avatar
3 ответов
+ 2
If you use the Pre/Postfix operators like ++, you need to remember that the incremented variable will be assigned that value! Do I'll go through it line by line: int x = 34;//declare and init new variable x of type int with the value 34 x is 34! int y = x++;//new integer: first use the value of x: y and x are 34! and only then increment x by one. x is 35 y is 34 int z = ++y;// new int: first increment the value of y: y is now 35, too! and then use the value: x remained untouched here and stays 35, y got incremented up to 35 and z is y, so 35 also. Got it?
26th Feb 2018, 8:23 PM
D B
D B - avatar
+ 17
int x = 34; int y = x++; //y=34++ , ie y=34 & x becomes 35 int z = ++y; //z=++34 , ie z=35 & y becomes 35
26th Feb 2018, 8:33 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 3
got it, thanks.
26th Feb 2018, 8:29 PM
Shariat Ullah Milon
Shariat Ullah Milon - avatar