Shallow Copy :
Shallow copy is a technique in which we have more than one reference variable pointing to the same object, means here we try to copy the reference of the object.
If we change anything in the object with the help of any one of the reference variable then that change will be reflected to all the reference variables.
Here we try to copy reference of object not creating a new object .
Shallow Copy Example
//ELC
class Test
{
public static void main(String []args){
Employee emp1 = new Employee(10000);
System.out.println(emp1.getSalary()); //
System.out.println(); //
Employee emp2 = emp1 ;
emp2.setSalary(20000);
System.out.println(emp1.getSalary()); //
System.out.println(emp2.getSalary()); //
}
}
// BLC class
class Employee
{
double salary;
Employee(double salary){
this.salary=salary;
}
public double getSalary(){
return this.salary;
}
public void setSalary(double salary){
this.salary = salary;
}
}
Deep Copy
- Deep copy is a technique in which always try to create a new Object .
- Generally we create new object with the help of
newKeyword . -
newkeyword is dynamic memory allocation operator . -
newkeyword always create a new object .
//ELC
class Test
{
public static void main(String []args){
Employee emp1 = new Employee();
Employee emp2 = new Employee(2000);
emp1.setSalary(emp2.getSalary());
System.out.println(emp1.getSalary());
System.out.println(emp2.getSalary());
System.out.println();
emp1.setSalary(80000);
System.out.println(emp1.getSalary());
System.out.println(emp2.getSalary());
}
}
// BLC class
class Employee
{
double salary;
Employee(){}
Employee(double salary){
this.salary=salary;
}
double getSalary(){
return this.salary;
}
void setSalary(double salary){
this.salary = salary;
}
}
Pass By Value :
- we have to type of variable .
Primitive variableReference variable
case 1 : when we pass Primitive Variable
- when we pass primitive variable then we pass actual value .
class Test
{
public static void main(String []args){
Test t1 = new Test();
int x = 10;
System.out.println(x);
t1.display(x);
System.out.println(x);
}
void display(int y ){
y = y+10;
}
}
case 2 : when we pass Reference Variable
- when we pass Reference variable then we pass Reference of Object not actual object .
- Means here we try to copy reference of object not creating Object .
- It is look like Shallow Copy concept ..




Top comments (0)