Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Arraylist.contains() Method in Java
Next article icon

clone() Method – Object Cloning in Java

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Object cloning in Java refers to creating an exact copy of an object. The clone() method in Java is used to clone an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.

Example 1: Here is a simple example demonstrating object cloning using the clone() method in Java.

Java
// Java program to demonstrate object cloning  // using the clone() method class GFG implements Cloneable {     int x, y;      // Constructor to initialize      // object fields     GFG() {         x = 10;         y = 20;     }      // Overriding the clone() method     @Override     public Object clone() throws CloneNotSupportedException {         // Returning a clone of the current object         return super.clone();      } }  public class Main {        public static void main(String[] args)        throws CloneNotSupportedException {         GFG o1 = new GFG();                   // Cloning obj1 into obj2         GFG o2 = (GFG) o1.clone();           System.out.println("o1: " + o1.x + " " + o1.y);         System.out.println("o2: " + o2.x + " " + o2.y);      } } 

Output
o1: 10 20 o2: 10 20 

Syntax of clone() Method

protected Object clone() throws CloneNotSupportedException

  • Return Type: It returns an Object type, which is a reference to the cloned object.
  • Exception: It throws a CloneNotSupportedException if the object’s class does not implement the Cloneable interface.

Example 2: Simple Object Cloning (Shallow Copy)

Here, we clone a simple object i.e. the shallow copy using the clone() method.

Java
// Java program to demonstrate  // object cloning (shallow copy) class GFG implements Cloneable {     String n;     int a;      // Constructor to initialize GFG object     public GFG(String n, int a) {         this.n = n;         this.a = a;     }      // Overriding clone() method      // to make it public     @Override     public Object clone() throws CloneNotSupportedException {         return super.clone();     }      @Override     public String toString() {         return "GFG{name:'" + n + "', age:" + a + '}';     } }  public class Main {        public static void main(String[] args) {         try {                        // Create a Person object             GFG p1 = new GFG("Ram", 24);              // Clone the Person object             GFG p2 = (GFG) p1.clone();              // Print both objects             System.out.println("Original: " + p1);             System.out.println("Cloned: " + p2);         } catch (CloneNotSupportedException e) {             e.printStackTrace();         }     } } 

Output
Original: GFG{name:'Ram', age:24} Cloned: GFG{name:'Ram', age:24} 

Explanation: In the above example, the clone() method is overridden in the GFG class to perform a shallow copy of the object. This creates a new object “p2” with the same values as the original object “p1”, but changes to immutable fields like String do not affect each other.

Example 3: Deep Copy with Object Cloning

Here, we demonstrate deep cloning by manually cloning referenced objects.

Java
// Java program to demonstrate // deep copy using clone()  // An object reference of this // class is contained by Test2 class Test {     int x, y; }  // Contains a reference of Test and // implements clone with deep copy. class Test2 implements Cloneable {     int a, b;      Test c = new Test();      public Object clone() throws CloneNotSupportedException     {         // Assign the shallow copy to         // new reference variable t         Test2 t = (Test2)super.clone();          // Creating a deep copy for c         t.c = new Test();         t.c.x = c.x;         t.c.y = c.y;          // Create a new object for the field c         // and assign it to shallow copy obtained,         // to make it a deep copy         return t;     } }  public class Main {     public static void main(String args[])         throws CloneNotSupportedException     {         Test2 t1 = new Test2();         t1.a = 10;         t1.b = 20;         t1.c.x = 30;         t1.c.y = 40;          Test2 t3 = (Test2)t1.clone();         t3.a = 100;          // Change in primitive type of t2 will         // not be reflected in t1 field         t3.c.x = 300;          // Change in object type field of t2 will         // not be reflected in t1(deep copy)         System.out.println(t1.a + " " + t1.b + " " + t1.c.x                            + " " + t1.c.y);         System.out.println(t3.a + " " + t3.b + " " + t3.c.x                            + " " + t3.c.y);     } } 

Output
10 20 30 40 100 20 300 40 

Explanation: In the above example, we can see that a new object for the Test class has been assigned to copy an object that will be returned to the clone method. Due to this, t3 will obtain a deep copy of the object t1. So any changes made in the ‘c’ object fields by t3, will not be reflected in t1.

Advantages of the clone() Method

  • If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.
  • If we use a copy constructor, then we have to copy all the data over explicitly i.e. we have to reassign all the fields of the class in the constructor explicitly. But in the clone method, this work of creating a new copy is done by the method itself. So to avoid extra processing we use object cloning.

Note: We can use the Assignment Operator to create a copy of the reference variable. This creates a shallow copy, means both variables will refer to the same object in memory. This is not the same as cloning, where a new object is created.



Next Article
Arraylist.contains() Method in Java

A

Ankit Agarwal
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • ArrayList in Java
    Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
    10 min read
  • ArrayList and LinkedList remove() methods in Java with Examples
    List interface in Java (which is implemented by ArrayList and LinkedList) provides two versions of remove method. boolean remove(Object obj) : It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present. Removes t
    3 min read
  • ArrayList get(index) Method in Java with Examples
    The get(index) method of ArrayList in Java is used to retrieve the element at the specified index within the list. Example 1: Here, we will use the get() method to retrieve an element at a specific index in an ArrayList of integers. [GFGTABS] Java // Java program to demonstrate the working of // get
    2 min read
  • Java ArrayList add() Method with Examples
    The add() method in the ArrayList class is used to add elements to the list. There are different versions of this method. Example 1: In this example, we will use the add() method to add elements at the end of the list. [GFGTABS] Java // Java Program to demonstrate Addition of // Elements to an Array
    2 min read
  • Java ArrayList addall() Method with Example
    The addAll() method in the ArrayList class is used to add all the elements from a specified collection into an ArrayList. This method is especially useful for combining collections or inserting multiple elements at once. Example: Here, we will add elements to the end of the list. [GFGTABS] Java // J
    2 min read
  • ArrayList clear() Method in Java with Examples
    The clear() method in the ArrayList class in Java is used to remove all elements from an ArrayList. After calling this method, the list becomes empty. Example 1: Here, we will use the clear() method to clear elements from an ArrayList of Integers. [GFGTABS] Java // Java program to demonstrate clear(
    2 min read
  • clone() Method - Object Cloning in Java
    Object cloning in Java refers to creating an exact copy of an object. The clone() method in Java is used to clone an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Example 1: He
    5 min read
  • Arraylist.contains() Method in Java
    In Java, the ArrayList contains() method is used to check if the specified element exists in an ArrayList or not. Example: Here, we will use the contains() method to check if the ArrayList of Strings contains a specific element. [GFGTABS] Java // Java program to demonstrate the use of contains() //
    2 min read
  • ArrayList ensureCapacity() Method in Java with Examples
    In Java, the ArrayList.ensureCapacity() method is used to increase the internal capacity of an ArrayList to ensure that it can hold a specified minimum number of elements. It helps to optimize performance by reducing the number of dynamic reallocations when adding a large number of elements. Example
    2 min read
  • ArrayList forEach() Method in Java
    In Java, the ArrayList.forEach() method is used to iterate over each element of an ArrayList and perform certain operations for each element in ArrayList. Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings. [GFGTABS] Java // Java program to demonstrate
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences