DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java

Trending

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Recurrent Workflows With Cloud Native Dapr Jobs
  1. DZone
  2. Coding
  3. Java
  4. Creating a Deep vs. Shallow Copy of an Object in Java

Creating a Deep vs. Shallow Copy of an Object in Java

There are two main ways to make copies: deep copy and shallow copy. Let’s explore these concepts and see how they work with some easy examples.

By 
Reza Ganji user avatar
Reza Ganji
DZone Core CORE ·
Sep. 05, 23 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
6.1K Views

Join the DZone community and get the full member experience.

Join For Free

When working with objects in Java, there are times when you need to create a copy of an object. However, not all copies are the same. In fact, there are two main ways to make copies: deep copy and shallow copy. Let’s explore these concepts and see how they work with some easy examples.

Deep Copy: What Is It?

Imagine you have a collection of shapes, each with its own set of properties. A deep copy of an object means creating a completely new copy of the original object, along with all the nested objects it contains. In other words, it’s like making a photocopy of each shape, including all the details.

Shallow Copy: What's the Difference?

On the other hand, a shallow copy is like making a copy of a picture and its frame. You get a new frame, but the picture itself remains the same. Similarly, a shallow copy of an object creates a new object, but it still shares the same nested objects with the original. Changes made to nested objects in the copied object will also affect the original object, and vice versa.

Let’s Put It Into Practice: Shapes Example

Imagine you have a class called Circle, which has a nested object of class Point representing its center. We'll see how deep copy and shallow copy work with these objects.

Java
 
public class Circle {
   public Point center;
    public int radius;

    public Circle(Point center, int radius) {
        this.center = center;
        this.radius = radius;
    }
}

public class Point {
        public int x, y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }


Creating a Shallow Copy

For a shallow copy, we just copy the references to the nested objects:

Java
 
public Circle shallowCopyCircle(Circle original) {
        return new Circle(original.center, original.radius);
 }


Creating Deep Copy

For a deep copy of a Circle, we need to create new instances of both the Point and the Circle objects:

Java
 
 public Circle deepCopyCircle(Circle original) {
        Point copiedPoint = new Point(original.center.x, original.center.y);
        return new Circle(copiedPoint, original.radius);
  }


Creating Simple CopyUtil Class

Here is the util class which has object copy codes:

Java
 
public class CopyUtil {
    public Circle deepCopyCircle(Circle original) {
        Point copiedPoint = new Point(original.center.x, original.center.y);
        return new Circle(copiedPoint, original.radius);
    }
    public Circle shallowCopyCircle(Circle original) {
        return new Circle(original.center, original.radius);
    }
}


Unit Tests

Let's write some simple tests to check our deep copy and shallow copy methods.

Java
 
public class ShallowAndDeepCopyUnitTest {

    @Test
    public void givenCircle_whenDeepCopy_thenDifferentObjects() {
        CopyUtil util=new CopyUtil();
        Point center = new Point(3, 5);
        Circle original;
        original = new Circle(center, 10);
        Circle copied = util.deepCopyCircle(original);
        assertNotSame(original, copied);
        Assert.assertNotSame(original.center, copied.center);
    }

    @Test
    public void givenCircle_whenShallowCopy_thenSameCenter() {
        CopyUtil util=new CopyUtil();
        Point center = new Point(7, 9);
        Circle original = new Circle(center, 15);
        Circle copied = util.shallowCopyCircle(original);
        assertNotSame(original, copied);
        assertSame(original.center, copied.center);
    }
}


Conclusion

Creating deep copies and shallow copies of objects in Java is like making copies of pictures and their frames. Deep copies duplicate everything, while shallow copies create new frames but share the same pictures. By understanding these concepts and applying them in your Java programs, you can ensure that your objects are copied in the way that best suits your needs. So remember, whether it's circles, squares, or any other objects, knowing how to copy them can make your Java programming smoother and more efficient.

Java (programming language) Object (computer science) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: