×

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java objects. The definition of a copy in Java and the distinction between a reference duplicate and an item copy will be covered first before going on to the shallow copy.

According to its name, a reference copy duplicates a reference variable pointing at an object. As an illustration, if we create a reference duplicate of a Byke object with a myByke variable pointing to it, the original object will still exist despite the two myByke variables.

A copy of an object is made of the actual object. So, if we were to copy our byke object once more, we could make a copy of the original and a second reference variable that pointed to it.

Shallow copy Java

A new object with the same instance variables as the original is said to be a shallow duplicate of the original. For instance, a shallow duplicate of a Set shares objects with the original Set by pointers and comprises the same members as the previous Set. Some claim that shallow copies employ reference meanings.

Shallow copy Java

Establishes a fresh reference to the exact memory location. In other words, we might conclude that only references are duplicated in shallow copy. As a result, the original and the object also refer to the same source. It's important to note that any modifications we make to the duplicated object's information also affect the original.

We copy all fields from the original objects whenever we generate a copy of an object that uses a shallow copy technique. However, only references to the objects, not the actual objects, are duplicated if it includes objects as the fields. It's important to note that only primitive data types are transferred but not the object references.

Shallow copy Java

Note: clone() method can default create the shallow object.

Take a look at the following code example.

Public class ShallowCopy  
{  
private int[] d;  
//this method will create a shallow copy 
public ShallowCopy(int[] value)   
{  
d= value;  
}  
public void displayData()   
{  
System.out.println(Arrays.toString(d) );  
}  
}  

Java Program for shallow copy

ShallowExample.java

//This program is for shallow copy in java
//import section
import java.io.*;
import java.util.*;
//creating the People class 
class People implements Cloneable   
{  
//a lower level of object
private Bike bike;  
private String names;  
public Bike getBike()   
{  
return bike;  
}  
public String getNames()   
{  
return names;  
}  
public void setName(String str)   
{  
names = str;  
}  
public People(String str, String temp)   
{  
names = str;  
bike = new Bike(temp);  
}  
public Object clone()   
{  
//shallow copy  
try   
{  
return super.clone();  
}   
catch (CloneNotSupportedException e)   
{  
return null;  
}  
}  
}  
class Bike   
{  
private String names;  
public String getNames()   
{  
return names;  
}  
public void setNames(String str)   
{  
names = str;  
}  
public Bike(String str)   
{  
names = str;  
}  
}  
//main section
public class ShallowExample 
{  
public static void main(String args[])   
{  
//Original Object of the class People 
People p1 = new People("People-A", "Civic");  
System.out.println("Exact Values (orginal values): " + p1.getNames() + " - "+ p1.getBike().getNames());  
// the clone contains the shallow object 
People q1 = (People) p1.clone();  
System.out.println("Clone (the changes before): " + q1.getNames() + " - "+ q1.getBike().getNames());  
//the primitive member of the clone has been changed  
//q1.setNames("People-B");  
//the lower level object has been changed
q1.getBike().setNames("Mossiac");  
System.out.println("Clone (after change): " + q1.getNames() + " - "+ q1.getBike().getNames());  
System.out.println("Original (the values after the modification of the clone object): " + p1.getNames()+ " - " + p1.getBike().getNames());  
}  
}  

Output

Shallow copy Java

ShallowExample2.java

//This program is for shallow copy in java
//import section
import java.io.*;
import java.util.*;
class XYZ
{  
// an instance variable n is created for the class XYZ  
int n = 30;  
}  
public class ShallowExample2   
{     
// Main method of the program 
public static void main(String argvs[])   
{  
//creating an object for the class XYZ  
XYZ object1=new XYZ();  
//the reference will be created, but the value is not copied
XYZ object2 = object1;  
// the value is updated to 10  
// using the reference variable object2  
object2.n=10; 
//the result is printed using the reference variable object1 
System.out.println("The number value is : " + object1.n);  
}  
} 

Output

Shallow copy Java

Shallow Copy Vs. Deep Copy

     Shallow copy     Deep copy
Original objects and cloned objects really aren't entirely distinct.Original items and cloned items don't connect at all.
Cloned objects can be modified and then imitated in original objects, or vice versa.An original thing can be altered and replicated in turn, or vice versa.
The clone() method's default implementation produces a shallow duplicate of an object.We must override the clone() function to construct the deep duplicate of an object.
A shallow copy is recommended if such an object contains just primitive fields. Should use a deep duplicate if an item contains references to those other items as fields.
It is much less costly and also quick.The Deep is very slow, and it is more expensive.
In Shallow copy, memory utilization is very efficient.As in the case of Deep copy, the memory utilization is not upto the mark.
It is very much efficient to error-prone.It is not efficient to error-prone.

Related Topics

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.