[Interview] Pass-by-value vs. Pass-by Reference

425 查看

Java is pass-by-value.

Pass by value: make a copy in memory of the actual parameter's value that is passed in.

Pass by reference: pass a copy of the address of the actual parameter.

This code will not swap anything:

void swap(Type a1, Type a2) {
    Type temp = a1;
    a1 = a2;
    a2 = temp;
}

For this code, since the original and copied reference refer the same object, the member value gets changed:

class Apple {
    public String color = "red";
}
public class main {
    public static void main(String[] args) {
        Apple a1 = new Apple();
        System.out.println(a1.color); //print "red"
        changeColor(a1);
        System.out.println(a1.color); //print "green"
    }
    public static void changeColor(Apple apple) {
        apple.color = "green";
    }
}

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

Some more examples

public class Main {
    public static void main(String[] args) {
        Student s = new Student("John");
        changeName(s);
        System.out.printf(s); // will print "John"
        modifyName(s);
        System.out.printf(s); // will print "Dave"
    }
    public static void changeName(Student a) {
        Student b = new Student("Mary");
        a = b;
    }
    public static void modifyName(Student c) {
        c.setAttribute("Dave");
    }
}
public static void changeContent(int[] arr) {
   // If we change the content of arr.
   arr[0] = 10;  // Will change the content of array in main()
}

public static void changeRef(int[] arr) {
   
   arr = new int[2];  // If we change the reference
   arr[0] = 15; // Will not change the array in main()
}

public static void main(String[] args) {
    int [] arr = new int[2];
    arr[0] = 4;
    arr[1] = 5;
    changeContent(arr);
    System.out.println(arr[0]);  // Will print 10..
    changeRef(arr);
    System.out.println(arr[0]);  // Will still print 10.. 
}