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.
7/9/2021 9:39:23 AM
Marc Cid Salmeron
6 Answers
New AnswerPrefix means ++X - increment and use Postfix means X++ - use and increment In your case int x = 34; int y = x++; //34 Int z = ++x; //36 I hope it clears your doubt
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
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
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.
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