How to Increment a class Integer references value in java from another method
No, objects aren't passed by reference. References are passed by value - there's a big difference. Integer
is an immutable type, therefore you can't change the value within the method.
Your n++;
statement is effectively
n = Integer.valueOf(n.intValue() + 1);
So, that assigns a different value to the variable n
in Increment
- but as Java only has pass-by-value, that doesn't affect the value of n
in the calling method.
EDIT: To answer your update: that's right. Presumably your "MyIntegerObj" type is mutable, and changes its internal state when you call plusplus()
. Oh, and don't bother looking around for how to implement an operator - Java doesn't support user-defined operators.
You could use an AtomicInteger
from java.util.concurrent.atomic
. It has a 'incrementAndGet' method which is suitable for your showcase.