Reference in Java

It's been a while we have learned how to create objects in Java. However today we would learn what's a Java reference. Reference refers to the object memory, reuse the object again and again.

Test obj=new Test() where Test is the name of the class whose object is created.

Here in the above syntax obj is the reference and new Test() allocates memory for the whole class. The new keyword creates memory repeatedly. To create the object we call the constructor.

public class Test {
int a=100,b=200, c=300;
Test(){
	System.out.println("default constructor");
}
	public static void main(String[] args) {
		//The new keyword allocates memory 3 separate times.
		System.out.println(new Test().a);
		System.out.println(new Test().b);
		System.out.println(new Test().c);
		
		Test t =new Test();
		//Here for the below case memory is allocated only once.
		System.out.println(t.a);
		System.out.println(t.b);
		System.out.println(t.c);
	}
}

//OUTPUT
/*default constructor
100
default constructor
200
default constructor
300
default constructor
100
200
300
*/

Did you know?

In Java, any address is called hashCode. It is the base address of an object.

Let us have a look at another example.



public class Test {
int x=100;
static Test obj1; //static reference
Test obj2; //non-static reference
	public static void main(String[] args) {
		Test obj3; //local reference
		System.out.println(obj1); //default value is null
		System.out.println(obj1.x); //Null pointer exception
		System.out.println(obj3); //ERROR, since local reference should be initialized before use.
		obj1=new Test(); //reference referring to object
		System.out.println(obj1); //hashcode, address of the Test class
		System.out.println(obj1.x); //100
		
		obj1.obj2=new Test(); //Initialize obj2
		System.out.println(obj1.obj2); //Hashcode
	}
}
  • Reference used to reuse the object memory. An object is the instance of class i.e. RAM memory.
  • An object can only be constructed by calling constructor and constructor is called using the new keyword.