Back to Arrays
Q9Question 9 of 109

Copy one array into another array

Key Concepts
  • Copying creates a new array of the same length and places each source element into the corresponding destination position.
  • Java offers four approaches: manual loop, System.arraycopy, Arrays.copyOf, and clone().
  • All four produce a shallow copy for object arrays, meaning references are duplicated but the objects themselves are shared.
  • Shallow copy is safe for immutable types like BigDecimal because the shared objects cannot be modified.
  • For mutable element types a deep copy is needed to make the arrays truly independent.
  • Time is O(n) and space is O(n) for the new array, regardless of which approach is used.

Definition

Make a fresh array of the same size and place each element into it; for objects this copies references, not the objects themselves.
  • New array – allocate a destination array of the same length as the source.
  • Element copy – place each source element into the corresponding destination position.
  • Shallow copy – for object arrays, references are duplicated but the objects themselves are shared.
  • Built-in methods – System.arraycopy, Arrays.copyOf, and clone() all perform shallow copies.
  • O(n) time and O(n) space – every copy must touch each element once and allocate a new array.

National Bank of India wants to archive Rajesh's current transaction list before running a risky interest recalculation. A clerk photocopies the whole list onto a fresh sheet so the original is safe. If the recalculation goes wrong, the archived copy is untouched and can be restored.

Understanding the Concepts

What is the problem?

Given a source array, create an independent copy. In a banking context, National Bank of India archives Rajesh's transaction list before a risky batch recalculation so the original can be restored if something goes wrong.

How do you copy with a manual loop?

Create a destination array of the same length and copy each element in a loop. This is the most explicit approach.

JAVA
package com.bank.service;

import java.math.BigDecimal;
import java.util.Arrays;

public class TransactionArchiver {

    public static BigDecimal[] copyManual(BigDecimal[] source) {
        BigDecimal[] dest = new BigDecimal[source.length];
        for (int i = 0; i < source.length; i++) {
            dest[i] = source[i];
        }
        return dest;
    }

    public static void main(String[] args) {
        BigDecimal[] original = {
            new BigDecimal("15000.00"),
            new BigDecimal("8200.00"),
            new BigDecimal("3400.50")
        };
        BigDecimal[] archive = copyManual(original);
        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Archive:  " + Arrays.toString(archive));
    }
}
TEXT
Original: [15000.00, 8200.00, 3400.50]
Archive:  [15000.00, 8200.00, 3400.50]

What built-in methods does Java provide?

Java offers three built-in alternatives, all producing the same shallow-copy result.

JAVA
// 1. System.arraycopy - native method, usually fastest
BigDecimal[] dest1 = new BigDecimal[source.length];
System.arraycopy(source, 0, dest1, 0, source.length);

// 2. Arrays.copyOf - allocates and copies in one call
BigDecimal[] dest2 = Arrays.copyOf(source, source.length);

// 3. clone - produces a new array with the same contents
BigDecimal[] dest3 = source.clone();

What is the difference between shallow copy and deep copy?

A shallow copy duplicates the references but not the objects. Both arrays point at the same BigDecimal objects. A deep copy creates new objects for each element so the two arrays are completely independent.

DIAGRAM
Shallow Copy:
  original[0] ──→ BigDecimal(15000.00) ←── archive[0]
  original[1] ──→ BigDecimal(8200.00)  ←── archive[1]

Deep Copy:
  original[0] ──→ BigDecimal(15000.00)
  archive[0]  ──→ BigDecimal(15000.00)  (separate object)

Why is shallow copy safe for BigDecimal?

BigDecimal is immutable. You cannot change the number inside a BigDecimal object; you can only create a new BigDecimal. So even though both arrays share the same objects, nobody can mutate a shared amount. Replacing a slot in one array does not affect the other array because replacement changes the reference, not the object.

When do you need a deep copy?

If the elements are mutable objects, such as a mutable Account object with a settable balance, a shallow copy is dangerous because modifying the object through one array is visible through the other. In that case you must clone each element individually.

JAVA
// Deep copy for mutable objects
Account[] deepCopy = new Account[source.length];
for (int i = 0; i < source.length; i++) {
    deepCopy[i] = new Account(source[i]); // copy constructor
}

What is the time and space complexity?

  • Time: O(n) because each element is copied once.
  • Space: O(n) because a new array of the same size is allocated.
  • All four approaches have the same complexity; System.arraycopy is often faster in practice because it is a native method that can use memory-level block copies.

What are common mistakes?

The most common mistake is assuming that assigning one array variable to another creates a copy. It does not; it just creates a second reference to the same array.

JAVA
// Wrong: not a copy, both variables point to the same array
BigDecimal[] archive = original; // changes to archive[0] affect original[0]

// Correct: create an actual copy
BigDecimal[] archive = Arrays.copyOf(original, original.length);

What should a senior engineer know?

A senior engineer knows that System.arraycopy is the most performant option because the JVM can use hardware-level memory copy instructions for contiguous blocks. The senior also knows that Arrays.copyOf internally delegates to System.arraycopy after allocating the destination array. For partial copies, Arrays.copyOfRange(source, from, to) copies a subarray, which is useful for copying a specific page of transactions from a larger array.

Visual Overview

DIAGRAM
  Shallow Copy:
  ┌─────────────────────┐     ┌─────────────────────┐
  │    original[]        │     │     archive[]        │
  │  [0] ref ──────────┐ │     │  [0] ref ──────────┐ │
  │  [1] ref ────────┐ │ │     │  [1] ref ────────┐ │ │
  │  [2] ref ──────┐ │ │ │     │  [2] ref ──────┐ │ │ │
  └────────────────┼─┼─┼─┘     └────────────────┼─┼─┼─┘
                   │ │ │                         │ │ │
                   │ │ └──→ BigDecimal(15000) ←──┘ │ │
                   │ └────→ BigDecimal(8200)  ←────┘ │
                   └──────→ BigDecimal(3400)  ←──────┘

Key Takeaway

Copying an array means creating a brand new array of the same length and placing each source element into the matching position of the destination. In Java I can do this with a simple loop, or with built-in helpers like System.arraycopy, Arrays.copyOf, or the clone method. All run in linear time and allocate a destination of the same size.

In my banking project at National Bank of India, I used array copying to take a backup before a risky interest recalculation. Before the batch job overwrites Rajesh's transaction amounts, I copy the original list into an archive array, so if the recalculation produces wrong figures I can roll back to the archived copy.

The subtle point I always raise is shallow versus deep copy. For an array of objects, these copy operations duplicate the references, not the objects themselves, so both arrays point at the same underlying objects. In my case the elements are BigDecimal, which is immutable, so a shallow copy is completely safe. If the elements had been mutable objects, I would need a deep copy that clones each element individually.

Remember one sentence: all Java array copy methods produce a shallow copy, which is safe for immutable types like BigDecimal but requires deep cloning for mutable elements.

---

Share
Use ← → arrow keys to navigate