[Java]What is the Object and Object reference ?


  • In Java, all objects are accessed by reference, and you never have direct access to the object itself.
  • Reference :- is a variable that has a name and can be used to access the contents of an object, A reference can be assigned to another reference passed to a method, or returned from a method.

    default value of object reference is  "null";


                 MyClass object ; 
  • Object:- is an entity that's exists in memory allocated by the Java run time environment, An object sits on the heap memory when we create an object like



                 MyClass object=new MyClass();

    It created the object and respective address and stored in the reference variable named "object".
  • Then what will happen if we create object with out reference like

     new MyClass();

    In this case object will be created in heap memory but there is no reference.
    So, you can't reuse this object.

       System.out.println(new MyClass().a);

    Once above statement is executed then garbage collector will destroy the object.

    Note: Garbage collector immediately won't invoke this is depends upon the CPU free time. Whenever CPU gets free time then it will come to destroy the unused and unreferenced object.










No comments:

Post a Comment