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 ?