1

I thought Arrays are static, i.e. they cannot be increased or decreased in element size. How come when I declare an array of x elements, I can copy an array of y>x elements into my new array like so:

import java.util.Arrays;

public class CopyOf {

public static void main(String[] args) {
    int[] array ={4,5,4,65,465,4,56,456,6,43,3,5,45};

    //copiedArray has 4 elements
    int[] copiedArray = new int[4];
     copiedArray = Arrays.copyOf(array, array.length);

    // copiedAarray now has 13 elements
    System.out.println(Arrays.toString(copiedArray));

    }

}

2 Answers 2

9

This

int[] copiedArray = new int[4];

Creates an array reference, and assigns it to a new array with space for 4 int(s). Then, this

copiedArray = Arrays.copyOf(array, array.length);

creates a new array and assigns it to copiedArray. The 4 int(s) created on the previous line are no longer reachable, and are now eligible for garbage collection.

Sign up to request clarification or add additional context in comments.

2 Comments

I think I understand it better. So copiedArray is pointing to an area in memory assigned for the array. When we use copyOf it is changing the reference address for copiedArray and is assigning it to a new area in memory. The 4int (s) isn't linked to any reference and so cannot be accessed but is still in memory. Is that correct?
@Crazypigs Correct. And since it isn't referenced it can now be garbage collected.
3

copiedArray changed its reference from array[4] to array[13]

Now variable array and copiedArray is pointing to the same object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.