Passing object as parameter into function


Please read following code.

public class Test {

    public static void main(String[] args) {
        // Integer reference called "clz"
        Integer clz = new Integer(1);
        changeValue(clz);
        System.out.println("After called changeValue(): " + clz.toString());
    }

    public static void changeValue(Integer input) {
        System.out.println("Start changeValue(): " + input);
        input = new Integer(2);
        System.out.println("Finish changeValue(): " + input);
    }

}

The output is

Start changeValue(): 1
Finish changeValue(): 2
After called changeValue(): 1

Finding

  1. Changing the value of reference (ie create a new object) inside a function will not affect the original value of reference passed into
  2. Before function is executed in JVM, value of reference "clz" copy to stack memory space "input". During execution, the change is on that stack memory space and after function is executed value of stack memory space will not copy back to original

Reference

  1. Passing String as parameter to a method