package myintergertest;
/**
*
* @author Engineering
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//this one does not increment
Integer n = new Integer(0);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
//this one will increment
MyIntegerObj myInt = new MyIntegerObj(1);
Increment(myInt);
System.out.println("myint = " + myInt.get());
Increment(myInt);
System.out.println("myint = " + myInt.get());
Increment(myInt);
System.out.println("myint = " + myInt.get());
}
public static void Increment(Integer n) {
//NO. this doesn't work because a new reference is being assigned
//and references are passed by value in java
n++;
}
public static void Increment(MyIntegerObj n) {
//this works because we're still operating on the same object
//no new reference was assigned to n here.
n.plusplus(); //I didn't know how to implement a ++ operator...
}
}
The result for all of those is n=0. Integer n is an object and therefore passed by reference, so why isn’t the increment reflected back in the caller method (main)? I expected output to be n=0 n=1 n=2 etc…
UPDATE:
Notice I updated the code example above. If I’m understanding correctly, Jon Skeet answered the question of why myInt would increment and why n does not. It is because n is getting a new reference assigned in the Increment method. But myInt does NOT get assigned a new reference since it’s calling a member function.
Does that sound like I understand correctly lol ?
No, objects aren’t passed by reference. References are passed by value – there’s a big difference.
Integeris an immutable type, therefore you can’t change the value within the method.Your
n++;statement is effectivelySo, that assigns a different value to the variable
ninIncrement– but as Java only has pass-by-value, that doesn’t affect the value ofnin 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.