Forums Register Login

anyone who can tell me?

+Pie Number of slices to send: Send
here is the code:
public class Inc {
public static void main(String[] args) {
Inc inc = new Inc();
int i = 0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}

the answer is 0 not 1.why ?
+Pie Number of slices to send: Send
i++ is a postfix operator so first a value is assigned and then the value will be increased by one.
If you use a prefix operator the result will be as you will expect.



For more information over postfix operators see the following link


Operators and Assignments - Prefix and Postfix Operators
+Pie Number of slices to send: Send
inc.fermin(i);

This call works on a local variable that is initialized with the value of i, 0. When in that method i++ is called, it increments that local variable, not the variable passed to the method.

i = i++;

Here's the real "magic". What happens here is something like the following:

Were you to write i++ it would have been 1. Had you written "i = ++i" it would have worked as well:

For more information, search for the difference between prefix and postfix increment.
+Pie Number of slices to send: Send
think you very much!
+Pie Number of slices to send: Send
Thanks for the reply.
Remko Strating
Rob Prime
Roses are red, violets are blue. Some poems rhyme and some don't. And some poems are a tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1038 times.
Similar Threads
interesting code
why output 0 for this question?
What is the output
i=i++?
simple one but Tricky !!
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 23:16:40.