+ 2

Increment & Decrement

I think I understood the prefix, but Im kinda lost with the postfix. public class Program { public static void main(String[] args) { int x = 34; int y = x++; System.out.println(y); //y=34 why Y isnt 35? What is it for? I mean, when do we use the postfix and how? Is the first time I see Increment/decrement and Prefix and postfix so I guess it will make sense once I study it more I.

9th Jul 2021, 9:39 AM
Marc Cid Salmeron
Marc Cid Salmeron - avatar
6 Answers
+ 2
Aysha z will be 36 After assigning value to y, x will be increase so x will be 35 then on ++x , x will be 36
9th Jul 2021, 10:01 AM
A͢J
A͢J - avatar
+ 1
Int x = 34; ~Post increment~ int y = x++; // this assigns x to y before incrementing, meaning y = 34 and x will be 35 ~Pre-increment~ Then int y = ++x; // this increments x first before it is assigned to y, meaning both x and y will have the value of 36. Would like to be corrected
10th Jul 2021, 4:10 PM
Vuyolwethu Mableka
Vuyolwethu Mableka - avatar
0
I mean, I know (or I think that I know) how it works, but I dont understand why, why should I use the postfix if using it I dont get any change :/ I guess it will make sense when I get used to it.
9th Jul 2021, 3:18 PM
Marc Cid Salmeron
Marc Cid Salmeron - avatar
0
if you're using them alone, that doesn't make difference... but if you're using while doing something else, that makes difference: x = 0; while (x<3) { System.out.println(x++); } // 0 1 2 x = 0; while (x<3) { System.out.println(++x); } // 1 2' 3
9th Jul 2021, 11:24 PM
visph
visph - avatar