Copy vs Reference

Lab Java Intermediate 20 points

Read n integers into a. Make b = a and c = Arrays.copyOf(a, n). Set b[0] = 99 and c[1] = -1, then print a, b and c with Arrays.toString.

Input

n (≥ 2), then n integers.

Output

Three lines.

Example

Input

3
1 2 3

Output

[99, 2, 3]
[99, 2, 3]
[1, -1, 3]
Sample input available Sample output available
Editor
Java

Hints

b = a copies the reference, so a and b are the same array.

Solution explanation

Arrays are objects: assignment copies the reference, not the contents. Use Arrays.copyOf or clone() for a real copy.

Show solution
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        int[] b = a;
        int[] c = Arrays.copyOf(a, n);
        b[0] = 99;
        c[1] = -1;
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(c));
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD