×

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 Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute 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.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.