int n = 5; n = n++; System.out.println(n);
Well, this prints out 5, can anyone explain please? Thanks!
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
int n = 5; n = n++; System.out.println(n);
Well, this prints out 5, can anyone explain please? Thanks!
See the response to Help with prefix/postfix
edit - nevermind
It is bad coding because n is initialized with 5, then n is incremented to 6 and then n is equal to 6.
When n is incremented to 6 it is the same thing as saying n = n + 1; n++ is called a short hand or idiom.
So what is happening is this...
int n = 5; n = (n = n + 1); System.out.println(n);
!!
No; it is bad code, but that's not what is happening, you've missed the whole point - the OP wants to know why the output is 5 instead of 6.
The result of the postfix expression is the original value; the increment operation is performed on the right hand expression value after the assignment and is, in this case, thrown away.