Passing object as parameter into function

Salad Lam - Jan 31 - - Dev Community

Notice

I wrote this article and was originally published on Qiita on 1 September 2021.


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);
    }

}
Enter fullscreen mode Exit fullscreen mode

The output is

Start changeValue(): 1
Finish changeValue(): 2
After called changeValue(): 1
Enter fullscreen mode Exit fullscreen mode

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player