Arrays.copyOf and Arrays.copyOfRange
What you'll learn: How to create new arrays by copying all or part of an existing array using Java's built-in utility methods.
Why Copy Arrays?
Sometimes you need a fresh array that's a duplicate or partial copy of another. You could create a new array manually and loop through copying elements, but Java provides faster, cleaner methods: Arrays.copyOf and Arrays.copyOfRange.
Arrays.copyOf: Full or Resized Copies
Arrays.copyOf creates a new array by copying elements from an existing array. You specify the new length:
int[] original = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOf(original, original.length);
// copy is now {10, 20, 30, 40, 50} — a complete duplicate
If the new length is larger, extra elements are filled with default values (0 for integers, false for booleans, null for objects). If smaller, only that many elements are copied:
int[] shorter = Arrays.copyOf(original, 3);
// shorter is {10, 20, 30}
int[] longer = Arrays.copyOf(original, 7);
// longer is {10, 20, 30, 40, 50, 0, 0}
Arrays.copyOfRange: Copying Specific Sections
Arrays.copyOfRange lets you copy a range of elements by specifying start and end indices (end is exclusive, like in loops):
int[] segment = Arrays.copyOfRange(original, 1, 4);
// segment is {20, 30, 40} — indices 1, 2, 3
This is perfect when you only need part of an array. The new array's length equals end - start.
Think of It Like Photocopying
Arrays.copyOf is like photocopying an entire document (and maybe adding blank pages). Arrays.copyOfRange is like copying just pages 5 through 10.
Key Takeaway: Use Arrays.copyOf(array, newLength) to duplicate or resize arrays, and Arrays.copyOfRange(array, fromIndex, toIndex) to extract specific sections into new arrays.