How to Copy an Array in Java


This example will explain how to copy an array in two ways.

Source Code


package com.beginner.examples;

import java.util.Arrays;

public class CopyArrayExample {


    public static void main(String[] args) {
        int[] nums = {2, 3, 6, 9};
        int[] copyNums = nums;
        int[] copyNumsSub = Arrays.copyOfRange(nums, 1, 3);
        System.out.println("nums:" + Arrays.toString(nums));
        System.out.println("CopyNums:" + Arrays.toString(copyNums));
        System.out.println("CopyNumsSub:" + Arrays.toString(copyNumsSub));

    }

}

``
`
Output:
`
``
nums: [2, 3, 6, 9]
CopyNums: [2, 3, 6, 9]
CopyNumsSub: [3, 6]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments