Primitive type vs Reference type in Java

We all are familiar with variables, in java variables represent a memory location that hold a value. During declaration of a variables, you are telling the compiler that what kind of value the variable can hold. For example a primitive type or a reference type. The following figure illustrate the difference between the both types.


Fig 1. A variable of primitive type holds the value of a primitive type whereas reference type holds a reference of an object stored in memory

int i = 1; 
int j= 2; 

Assigning the value of j to i, i is set the value of j having the same value as j have.


Fig 2. Primitive value j is copied to i

Let’s consider the class circle.

public class Circle { 
 double radius; Circle(double r) { 
   radius = r; 
 double getArea() { 
  return radius * radius * Math.PI; 

Creating two objects c1 and c2.

 Circle c1 = new Circle(5.0); 
Circle c2 = new Circle(9.0); c1=c2; 

Fig 3. Reference variable c2 copied to c1

In case of reference variable,  assignment statement c1= c2. Reference variable c1 one updated. Now c1 and c2 are pointing the same memory location. It means c1 and c2 are holding the the same information as shown in fig 3.


  1. Reply

    • By Gul


  2. Reply

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.