Java-Assigning Object Reference

Assigning Object Reference

We are assign one object reference variable to another object reference variable, we are not creating a copy of the object, we are only making a copy of the reference. For example, in the following program, the object references d1, d2 and d3 will point to the same object. Therefore, any change that we make to the object referenced by d3 will also affect the same objects d2 and d1 is referring. We can create multiple references to the same object.

Program

dsdsds

Program Source

class Data{
    
    int data1;
    int data2;
}

public class Javaapp {

    public static void main(String[] args) {
       
        Data d1  = new Data();
        d1.data1 = 20;
        Data d2  = d1;
        d2.data2 = 40;
        Data d3  = d2;
        System.out.println("d3.data1 : "+d3.data1);
        System.out.println("d3.data2 : "+d3.data2);
    }
}

Leave a Comment