Pass by Value Demo

Problem

Read an integer n. Create an array with the elements 1, 2, 3. Then call three helper functions: (1) change(number) adds 100 to its parameter, (2) setFirst(array) sets the first element of the array to 99, (3) replace(array) assigns a NEW array {7, 8, 9} to its parameter. Print three lines: number after call: <n>, array first element after call: <value>, reassigned array first element: <value>. Java always passes a copy of the value: for objects the value is the reference.

Constraints

  • -2^31 <= n < 2^31

Examples

Input

5

Output

number after call: 5
array first element after call: 99
reassigned array first element: 99

Solutions

Best approachTime O(1)Space O(1)

Java passes everything by value. A number is copied. An object reference is also copied, so both the caller and the method point to the same object. Changing the object is visible; assigning a new object to the parameter is not. JavaScript and Python behave the same way.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Show pass by value.
 * Input   : One integer.
 * Output  : Three lines.
 * Approach: Copies of values and references.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // This method receives a COPY of the number. The change is lost when the method ends.
        static void change(long number) {
            number = number + 100;
        }

        // This method receives a COPY of the reference, but it points to the SAME array. The change is visible outside.
        static void setFirst(int[] array) {
            array[0] = 99;
        }

        // This method changes only its own copy of the reference. The caller still points to the old array.
        static void replace(int[] array) {
            array = new int[] {7, 8, 9};
        }

    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(long n) {
        // Step 1: Start with a number and an array.
        int[] array = {1, 2, 3};

        // Step 2: Call the three methods.
        change(n);
        setFirst(array);
        replace(array);

        // Step 3: Print what the caller can see.
        return new String[] {
            "number after call: " + n,
            "array first element after call: 99",
            "reassigned array first element: " + array[0]
        };
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(String.join("\n", solve(n)));
    }
}
Hints (1)
  1. Does assigning a new array to the parameter change the caller's array?