In Java, a class is a blueprint. An object is a real instance created from that blueprint.
We create objects using the new operator, which allocates memory and returns a
reference to that object.
ClassName variableName = new ClassName(parameters);
Examples:
String name = new String("Tiger");
Scanner input = new Scanner(System.in);
Random rand = new Random();
Each statement:
A variable that holds an object does not store the object directly. Instead, it stores a reference (a memory address pointing to the object in the heap).
Student s1 = new Student("Aiden", 11);
Here:
Student object is created in memorys1 stores the memory location of that objectTwo variables can point to the same object.
Student a = new Student("Maria", 12);
Student b = a;
Both variables:
Declaring a reference variable without creating an object:
Student s;
Setting a reference to null:
Student s = null;
A null reference points to no object. Calling a method on a null reference:
s.getName();
will cause a NullPointerException.
When we use new, Java places the object in a memory area called the
heap.
Reference variables (like s1 or rand) live in
stack memory and only hold the address of the object on the heap.
Java automatically removes objects from memory when no references point to them.
Student s = new Student("Luis", 10);
s = new Student("Emma", 12);
The first object (“Luis”) has no references and becomes garbage. Java’s garbage collector will remove it later.
new operator