Java assigning object reference



Assigning Object Reference Variables : Class Concept in Java Programming

  1. We can assign value of reference variable to another reference variable.
  2. Reference Variable is used to store the address of the variable.
  3. Assigning Reference will not create distinct copies of Objects.
  4. All reference variables are referring to same Object.

Assigning Object Reference Variables does not –

  1. Create Distinct Objects.
  2. Allocate Memory
  3. Create duplicate Copy

Consider This Example –

Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
  • r1 is reference variable which contain the address of Actual Rectangle Object.
  • r2 is another reference variable
  • r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does not create duplicate object , nor does it allocate extra memory.

Assigning Object Reference Variables in Java Programming[468×60]

Live Example : Assigning Object Reference Variables

class Rectangle {
  double length;
  double breadth;
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle();
  Rectangle r2 = r1;

  r1.length = 10;
  r2.length = 20;

  System.out.println("Value of R1's Length : " + r1.length);
  System.out.println("Value of R2's Length : " + r2.length);

  }
}

Output :

C:Priteshjava>java RectangleDemo
Value of R1's Length : 20.0
Value of R2's Length : 20.0

Typical Concept :

Suppose we have assigned null value to r2 i.e

Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
.
.
.
r1 = null;

Note : Still r2 contain reference to an object. Thus We can create have multiple reference variables to hold single object.
[468×60]