Ad space (banner)
โ˜•Java Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

This lesson covers the difference between a shallow copy and a deep copy in Java, so you can avoid bugs caused by unintended data sharing. It's for anyone searching "Java shallow copy deep copy."

Assigning a Java class instance to another variable actually copies "a reference pointing to the same thing." This is a "shallow copy" for a class, and changing one affects the other.

The example makes shallow point to the same Address instance as original with Address shallow = original. Changing it with shallow.city = "Osaka" means original.city also shows "Osaka" when displayed.

A common early mistake is the bug of "I thought I made a copy, but the original data changed too." Understanding the difference between a reference type and a value type is unavoidable knowledge for correctly working with how Java handles memory.

In real projects, if you genuinely want to duplicate an object independently, you need to write your own dedicated deep-copy logic.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)