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 pageshowhide
explore
- Array Declaration and Creation5 questions
- Array Bounds Checking5 questions
- Multidimensional and Jagged Arrays5 questions
- Array Covariance and ArrayStoreException4 questions
- Arrays Utility Methods6 questions
- System.arraycopy and Array Copying5 questions
- Array vs ArrayList Trade-offs5 questions
questions
page 2 of 2Why is System.arraycopy typically faster than copying an array with a manual for-loop?
basics
~20 sSystem.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.
How do you use System.arraycopy to insert or remove an element within the same array, and why is the in-place overlap correct?
basics
~20 sTo 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.
What exceptions can System.arraycopy throw, and when can a copy be left partially completed?
basics
~20 sIt 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.
How do bounds checks work for multidimensional arrays, and what role does this safety guarantee play in the JVM's overall memory-safety model?
basics
~20 sA 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.
What runtime mechanism makes covariant array stores safe, and what are its costs and design implications?
basics
~20 sThe 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.
showing 31–35 of 35