Skip to lesson

Assignment is not a copy

Assigning one object variable to another does not copy the object. b = a copies only the reference, so both names lead to one object. A real copy is a second object, made with new, that starts with the same data.

b = a copies the reference, not the object

A reference copy, or aliasing, is what b = a does with object variables: only the reference is copied, so both variables point to the same object. A change made through one variable is seen through the other.

Diya's marks need a correction, and you want a spare record to try it on first. Student b = a; looks like a copy, but as in Many objects, references and null (opens in a new tab), it copies only the reference.

Left: after Student b = a; and b.marks = 90, a and b both point to one Student object (Diya, marks 90), so a.marks is 90 too. Right: after b = new Student(a.name, a.marks); and b.marks = 90 there are two objects: a keeps marks 82 and b has 90.

Example 1 · One object, two names

SharedReferenceDemo.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
public class SharedReferenceDemo {    public static void main(String[] args) {        Student a = new Student("Diya", 82);        Student b = a;
        b.marks = 90;
        System.out.println("a.marks = " + a.marks);        System.out.println("b.marks = " + b.marks);        System.out.println("a == b: " + (a == b));    }}
Output
a.marks = 90
b.marks = 90
a == b: true

What this code does

  • Student b = a; copies the reference, so a and b point to the one object made by new.
  • b.marks = 90 changes that object, so a.marks is 90 too, and a == b is true: the spare record was never a spare.

Assignment never creates an object. A new object comes only from new, or from a method that calls new inside, such as Arrays.copyOf. So "one new, one object", however many variables point to it.

When sharing is a bug

The fees office fills two receipts from one ready-made template, a starting object with the common details. With =, every "receipt" is the template itself, so the last details written win.

Example 2 · Mistake: one template shared by every receipt

ReceiptBugDemo.javaJava
class Receipt {    String college;    String student;    int amount;
    Receipt(String college, String student, int amount) {        this.college = college;        this.student = student;        this.amount = amount;    }
    @Override    public String toString() {        return college + " | " + student + " | Rs " + amount;    }}
public class ReceiptBugDemo {    public static void main(String[] args) {        Receipt template = new Receipt("City Engineering College", "-", 0);
        Receipt forArjun = template;        forArjun.student = "Arjun";        forArjun.amount = 45000;
        Receipt forKavya = template;        forKavya.student = "Kavya";        forKavya.amount = 52000;
        System.out.println(forArjun);        System.out.println(forKavya);        System.out.println(template);    }}
Output
City Engineering College | Kavya | Rs 52000
City Engineering College | Kavya | Rs 52000
City Engineering College | Kavya | Rs 52000

What this code does

  • The fees office meant to make two receipts from one template. But forArjun, forKavya and template are three names for one object.
  • Filling in Kavya's details overwrote Arjun's, and even the template changed. There is no error, only wrong output.

Sharing is a bug whenever each side expects its own version: a template, a backup kept for undo, or a "what if" change such as trying a discount without touching the real price. Java gives no error; the output is simply wrong.

Sharing is right when there really is one thing, like one song in many playlists in Aggregation (opens in a new tab). The question is always: should a change on one side show on the other?

A real copy is a new object

An object copy is a separate object, created with new, whose fields start with the same values as the original. After that the two change independently: a change to one never shows in the other.

To give each receipt its own object, call new and pass in the template's values: new Receipt(template.college, template.student, template.amount).

Example 3 · Fix: a new object for each receipt

ReceiptCopyDemo.javaJava
class Receipt {    String college;    String student;    int amount;
    Receipt(String college, String student, int amount) {        this.college = college;        this.student = student;        this.amount = amount;    }
    @Override    public String toString() {        return college + " | " + student + " | Rs " + amount;    }}
public class ReceiptCopyDemo {    public static void main(String[] args) {        Receipt template = new Receipt("City Engineering College", "-", 0);
        Receipt forArjun = new Receipt(template.college, template.student, template.amount);        forArjun.student = "Arjun";        forArjun.amount = 45000;
        Receipt forKavya = new Receipt(template.college, template.student, template.amount);        forKavya.student = "Kavya";        forKavya.amount = 52000;
        System.out.println(forArjun);        System.out.println(forKavya);        System.out.println(template);        System.out.println("forArjun == template: " + (forArjun == template));    }}
Output
City Engineering College | Arjun | Rs 45000
City Engineering College | Kavya | Rs 52000
City Engineering College | - | Rs 0
forArjun == template: false

What this code does

  • Each new Receipt(...) makes a separate object that starts with the template's values. That is a real copy.
  • All three tests pass: forArjun == template is false, each copy started with the same data, and filling in a copy leaves the template unchanged.

Test any copy three ways: copy == original must be false (two objects, as in == and references (opens in a new tab)), the data must match, and changing the copy must leave the original as it was.

Listing every field outside the class gets long, and it breaks when a field is added. Copy constructors (opens in a new tab) move the copying into the class.

Predict the output

Copy or shared?

Read the code and pick what it prints.

Round 1 of 3

yours is assigned from mine. What does the program print?

class Phone {
String model;
int storageGb;
Phone(String model, int storageGb) {
this.model = model;
this.storageGb = storageGb;
}
}
public class Main {
public static void main(String[] args) {
Phone mine = new Phone("Redmi Note 13", 128);
Phone yours = mine;
yours.storageGb = 256;
System.out.println(mine.storageGb);
}
}

Copying arrays: clone() and Arrays.copyOf

A re-test changes one mark, and the old marks must stay. An array is an object, so int[] b = a; shares it, as in Arrays and methods (opens in a new tab). Two calls make a real array copy.

Example 4 · Copying an array three ways

ArrayCopyDemo.javaJava
import java.util.Arrays;
public class ArrayCopyDemo {    public static void main(String[] args) {        int[] marks = {72, 85, 90};
        int[] same = marks;        int[] copy1 = Arrays.copyOf(marks, marks.length);        int[] copy2 = marks.clone();        int[] longer = Arrays.copyOf(marks, 5);
        marks[0] = 0;
        System.out.println("marks  = " + Arrays.toString(marks));        System.out.println("same   = " + Arrays.toString(same));        System.out.println("copy1  = " + Arrays.toString(copy1));        System.out.println("copy2  = " + Arrays.toString(copy2));        System.out.println("longer = " + Arrays.toString(longer));        System.out.println("marks == same: " + (marks == same));        System.out.println("marks == copy2: " + (marks == copy2));    }}
Output
marks  = [0, 85, 90]
same   = [0, 85, 90]
copy1  = [72, 85, 90]
copy2  = [72, 85, 90]
longer = [72, 85, 90, 0, 0]
marks == same: true
marks == copy2: false

What this code does

  • same shares the array, so it shows the 0. copy1 and copy2 are new arrays, so they keep 72.
  • Arrays.copyOf(marks, 5) makes a longer array and fills the two extra slots with 0, the default for int.
  • marks == copy2 is false: clone() really made a second array.

Example 5 · An array of objects: new array, same students

ArrayOfObjectsCopyDemo.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
public class ArrayOfObjectsCopyDemo {    public static void main(String[] args) {        Student[] toppers = { new Student("Diya", 95), new Student("Arjun", 91) };        Student[] backup = toppers.clone();
        backup[1] = new Student("Kavya", 93);        backup[0].marks = 50;
        System.out.println(toppers[0].name + " " + toppers[0].marks);        System.out.println(toppers[1].name + " " + toppers[1].marks);        System.out.println(backup[1].name + " " + backup[1].marks);        System.out.println("toppers == backup: " + (toppers == backup));        System.out.println("toppers[0] == backup[0]: " + (toppers[0] == backup[0]));    }}
Output
Diya 50
Arjun 91
Kavya 93
toppers == backup: false
toppers[0] == backup[0]: true

What this code does

  • clone() made a new array, so putting Kavya in backup[1] did not touch toppers[1].
  • But the slots of both arrays point to the same Diya object, so backup[0].marks = 50 changed the topper list too.

Arrays.copyOf, from The Arrays class (opens in a new tab), can also change the length; clone() always keeps it. Both copy only what sits in each slot. For an array of objects that is a reference, so the students are still shared: Shallow vs deep copy (opens in a new tab) fixes that.

Next step

Check your understanding

12 quick questions