Reference Variable in Java

Before We Started with Reference variable we should know about the following facts.

Firstly when we create an Object(instance) of class then a space is reserved in a heap memory.

Lets understand with the help of an Example:

Demo D1 = new Demo();

blog1_1.JPG

Now , The space in the heap Memory is created but the question is "how to access that space".

Then , We create a Pointing element or simply called Reference variable which simply point out the Object(The Created Space in a Heap Memory).

blog1_2.JPG


Understanding Reference variable :

  1. Reference variable is used to point object/Values .
  2. Classes, interfaces, arrays, enumerations and, annotations are the in Java are reference types in Java. Reference variables hold the objects/values of reference types in Java.
  3. Reference variable can also store null value. By default if no object is passed to a reference variable then it will store null value.
  4. You can access object members using reference variable using following syntex :

reference variable name . instance variable_name / method_name

Now , We gonna know what is actually happening in the CODE

LET's TAKE AN EXAMPLE:

class Demo
{
      int x = 10;                        
      void display()        
      {
         System.out.println("x = "+x);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo D1 = new Demo();              // point 1
       System.out.println(D1);             // point 2
       System.out.println(D1.display());  //point 3
  }
}

OUTPUT: Demo@7ab292b7
10

Here, At point 1:
When we create an object of demo classnew DEMO();,suddenly default constructor has called and returns a reference of object , and simply this reference will stored to the reference variable D1 (As we know that associativity is Right hand side to left hand side).

Again At point 2:
the value of a reference variable is a reference. When we attempt to print the value of a reference variable, the output contains the type of the variable and an identifier created for it by Java: the string Demo@7ab292b7 tells us that the given variable is of type Name and its identifier is 7ab292b7.

At point 3:
At this point we will access the methods (display()) of class demo using our custom reference variable that we created.

BINDING UP : The constructor call returns a value that is a reference to the newly-created object. The equality sign tells the program that the value of the right-hand side expression is to be copied as the value of the variable on the left-hand side. The reference to the newly-created object, returned by the constructor call, is copied as the value of the variable.


class Demo
{
      int x = 10;                        
      void display()        
      {
         System.out.println("x = "+x);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo D1 = new Demo();           
       System.out.println(D1.x);    // accessing instance(object) variable
       D1.display();  //point 3        // accessing instance(object) method
  }
}

OUTPUT: 10
10

In the following code: D1 access the instance members.

blog1_3.JPG


class Demo
{
      int x = 10;                        
      void display()        
      {
         System.out.println("x = "+x);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo D1 = new Demo();           
       Demo M1 = new Demo();
       Demo Q1 = new Demo();
  }
}

blog1_4.JPG


class Demo
{
      int x = 10;                        
      void display()        
      {
         System.out.println("x = "+x);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo D1 = new Demo();           
       Demo G1 = D1;
       Demo M1 = new Demo();
       Demo Q1 = M1;

       G1.x = 25;          // updating the value of x using G! reference variable
       System.out.println(G1.x);   //Point 1
       System.out.println(D1.x);   // Point 2
  }
}

< OUTPUT : 25
25 blog1_5.JPG

Here we pass G1 and Q1 reference variable point out the same object respectively.
Secondly At Point 1 we try to get the value of object with G1 reference variable which shows it as 25 and At Point 2we try to get the value of object with D1 reference variable which shows it as 25 as well "" This will proves that the modification in the object can be done by using any reference variable but the condition is it should hold the same reference.


More On "REFERENCE VARIABLE" :

1. Reference Variable as Method Parameters:

As the value of a primitive variable is directly stored in the variable, whereas the value of a reference variable holds a reference to an object. We also mentioned that assigning a value with the equality sign copies the value (possibly of some variable) on the right-hand side and stores it as the value of the left-hand side variable.

A similar kind of copying occurs during a method call. Regardless of whether the variable is primitive or reference type, a copy of value passed to the method's argument and copied to that argument .

NOTE : JAVA ONLY SUPPORTS PASS BY VALUE

BUT we know that reference variable hold the reference of instance(OBJECT) so a copy of reference passed to the method's argument.
Let's Understand by the help of an example:

class Demo
{
      int x = 10;  
      int y = 20;                     
      void display(Demo A,Demo B)        
      { 
         A.x = 95;                          //  Updating value using argument
         System.out.println("x = "+x);
         System.out.println("y = "+y);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo C = new Demo();
       Demo D = new Demo();
       D.y = 55;             // updating value using primary reference variable
       C.display(C,D);           // POINT 1
       D.display(C,D);           // POINT 2
  }
}

OUTPUT
95 20
10 55

SCENE 1: blog1_6.JPG
SCENE 2:

blog1_7.JPG
Now , what is going on here , when we pass the reference to the method it will copy to the reference variable defined in method signature and After that they also have access to the object members.
Here, We defined two instances named C and D afterwards we pass C and D to the method which further give reference to A and B
AT POINT 1: A will update the value of x from 10 to 95,hence C.display() will show 95 20 but in another object D we update the value of x trough D only from y =20 to 55,hence D,display() will show 10 55

NOTE :ANY OBJECT'S UPDATION WILL NOT AFFECT OTHER OBJECT's MEMBER


What if we swap the reference variables with the help of Swap Method?

Ans: The fact is if we try to swap the reference variable, then they just swap their Pointing element there is no effect on the address of reference variable and object(Instance) Space .
Let's Understand It by the help of an example:

class Demo
{               
      void Swap(Demo A,Demo B)        //Swapping Method 
      { 
            Demo temp = A;
            A = B;
            B = temp;         
     }
}
class Main
{
 public static void main(String[] args)
   {
       Demo C = new Demo();
       Demo D = new Demo();
       C.Swap(C,D);     // Passing C and reference variables to Swap method
  }
}

Here we created, two instances of demo class and passes it to swap method ,further those C and D will copy their references to A and B respectively.Before swapping A point to C's(Object) and B point to D's(Object). After we perform swapping on A and B ,A will now point D's(Object) and B will Point C's Object. As described in the figure.

blog1_8.JPG

Note: There is no swapping between Variables , They only change their References.


3.What if we pass arrays to the method will it be able to update the Actual Array's values , even we know that a copy of array is pass to the formal Array?

Ans: The answer is YES the values will updated by Formal parameter, The Fact is , When we create an Array ,a memory is assign to the array
of desired size, and it returns the reference of first array's element that is base address that will store to the Formal Array(Method argument).
And as we learned earlier every pointing reference variablr can change or update the object.

blog1_9.JPG


Example:

class Demo
{               
      void arrayUpdate(int [] formalArray )        
      { 
          formalArray[2] = 99; 
          formalArray[4] = 77;    
      }
}
class Main
{
 public static void main(String[] args)
   {
        int [] actualArray  = {1,2,3,4,5};

        For(int items : actualArray)
            System.out.print(items+" , ");  //printing array    

         arrayUpdate(actualArray);

        For(int items : actualArray)
            System.out.print(items+" , ");  //printing array

    }
}

OUTPUT
1 , 2 , 3 ,4 , 5
1 , 2 , 99 ,4 , 77


4. (This) and (super) keywords are also Pointing Elements.

  • this keyword. In java, (this) is a reference variable that refers to the current object.

thisr.jpg

  • super is used to refer immediate parent class instance variable. We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.

Clipboard01.jpg


5. (null )value of a reference variable

Demo Kuchbhi = null;

  1. The null reference can be set as the value of any reference type variable.
  2. The object whose name is Kuchbhi is referred to by nobody. In other words, the object has become "garbage". In the Java programming language the programmer need not worry about the program's memory use. From time to time, the automatic garbage collector of the Java language cleans up the objects that have become garbage. If the garbage collection did not happen, the garbage objects would reserve a memory location until the end of the program execution.
class Demo
{
      int x = 10;                        
      void display()        
      {
         System.out.println("x = "+x);
      }
}
class Main
{
 public static void main(String[] args)
   {
       Demo Kuchbhi = null;           

       D1.display();          // accessing instance(object) method
  }
}

OUTPUT
Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:(row)) Java Result: 1

here, we try to access objects's member by a reference variable which is pointing nothing(null) and hence it shows NullPointerException

now if you get the error , the first step is to look for variables whose value could be null. Fortunately, the error message is useful: it tells which row caused the error. Just Try it out yourself!