I ran the following code snippet
int n=0;
for(int m=0;m<5;m++){
n=n++;
System.out.print(n)}
I got the output as 00000 when i expected 01234. Can someone explain why
Thanks in advance
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
n=n++;should be justn++;orn=n+1;(or evenn=++n;if you want)n++does the increment but will return the value ofnbefore the increment took place. So in this case you’re incrementingn, but then settingnto be the value before the increment took place, effectively meaningndoesn’t change.The
++operator can either be used as prefix or postfix. In postfix form (n++) the expression evaluates ton, but in the prefix case (++n) the expression will evaluate ton+1. Just using them on their own has the same outcome though, in thatn‘s value will increment by 1.