From classes many instances (objects) can be made.
Declaration where the reference will point to null:
ClassName objectName;
Memory allocation:
objectName = ...;
Declaration and memory allocation by invoking a constructor method of the object:
ClassName objectName = new ClassName(...);
Passing a temporary object created with its constructor, to a method; outside the scope of method the object will not exist:
methodName(new ClassName());
EXAMPLE FOR CLASS AND ITS OBJECT IN DIFFERENT CLASSES:
EXAMPLE FOR CLASS AND ITS OBJECT IN SAME CLASS:
EXAMPLE FOR PASSING TEMPORARY OBJECT TO METHOD 1:
EXAMPLE FOR PASSING TEMPORARY OBJECT TO METHOD 2:
It is a good practice to have private fields and public constructors, getter and setter methods.
String is a wrapper class. Declaration of a String sets its value to "" instead of pointing to null.
By creating an object in memory, Java will generate a unique number (hashcode) to it. With hashcode, the object can be referenced.
For the same type of immutable objects, Java will use memory pools, and upon creation, if the object with the same value already exists in the pool, will use hashcode of the existing object in order to reserve memory space.
By using constructor of a class to create new object, Java will skip searching for existing objects in the pool but create a new one.