skip to content

Arrays

Java arrays: how you declare and create them, the fixed length, jagged multidimensional forms, covariance, and the Arrays and System helpers. Interviewers use arrays to contrast with generics and with ArrayList.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

Why is System.arraycopy typically faster than copying an array with a manual for-loop?

level: seniorimportance: should knowfreq 42%

basics

~20 s

System.arraycopy is implemented inside the JVM as a single block memory copy, so it moves many bytes at once instead of one element per loop iteration. A hand-written for-loop does an array bounds check and a separate store on every element.

open as a page

How do you use System.arraycopy to insert or remove an element within the same array, and why is the in-place overlap correct?

level: seniorimportance: should knowfreq 35%

basics

~20 s

To remove an element you shift the elements after it one slot left; to make room for an insert you shift them one slot right. You call System.arraycopy with the same array as both source and destination — it handles the overlapping ranges correctly.

open as a page

What exceptions can System.arraycopy throw, and when can a copy be left partially completed?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

It throws NullPointerException if either array is null, IndexOutOfBoundsException if any index or the length goes out of range, and ArrayStoreException if an element type does not fit the destination. For object arrays, an ArrayStoreException can happen after some elements were already copied.

open as a page

How do bounds checks work for multidimensional arrays, and what role does this safety guarantee play in the JVM's overall memory-safety model?

level: principalimportance: nice to knowfreq 25%

basics

~20 s

A 2D array in Java is really an array of arrays, so each level is bounds-checked separately. This per-access checking is part of why the JVM is memory-safe: no Java code can read or write outside an allocated object's bounds.

open as a page

What runtime mechanism makes covariant array stores safe, and what are its costs and design implications?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

The JVM checks every store into a reference array against the array's real element type, throwing ArrayStoreException on a mismatch. This costs a small per-store check and is part of why invariant generics were preferred for new APIs.

open as a page

showing 31–35 of 35