Skip to main content

Life Time of Objects in Java with code Examples


Lifetime Concept in Java Programming

  • Time between allocation and de-allocation of memory
  • Life time depends on block i.e { } 
  • life time starts when declaration statement elaborated and expires at end of block 
  • There is no delete keyword in java 
  • Garbage collector is responsible for all deletes
  • Java is free from dangling reference and garbage problem


Why java does not support delete keyword?
  • Java does not support delete keyword because there is a garbage collector in java
  • This automatically runs and collects dangling or un-referenced objects.That is why there is no delete keyword in java like C++.
  • Garbage collector can be explicitly like that System.gc(); 
  • When a life of object ends garbage collector runs automatically

  • Example 1


{
int a=5;// life Time start here
a++;
} //life time expire

Example 2
  Let Student is a class
Student s;   // creating a reference of Student class
   {Student t; // l
     t= new Student(); // Life Time Start
     s=t;
   }//garbage collector expires Student t reference from stack

When life of an object ends it is available for garbage collector to collect. 

Example 3

   {Student t;
     t= new Student(); // Life Time Start
     t= new Student();
     t= new Student();
     t= new Student();

   }//life time expires


Note: We can explicitly request garbage collector to invoke using System class gc method but it will again depends of garbage thread
    System.gc();

Example 4

   {Student t;
     t= new Student(); // Life Time Start
     System.gc();      // invokeing garbage collector
     t= new Student();
     t= new Student();
     System.gc();
     t= new Student();

   }//
Destructors in java

  •  No explicit destructors in java as c++
  • finalize method can be used as action on expiry
 protected void finalize() {}
Example 
class Car{
String make;
Car (String m){make=m;}
String getMake() { return make;}
void setMake(String m){make=m;}
protected void finalize(){
// action on expiry
}
}

There are no explicit pointers in java like C++
Problem with Pointers

1- Garbage (Memory Leakage)
  c++
    Student *t;
     t= new Student(); // Life Time Start
     t= new Student();
     t= new Student();
     t= new Student();

2- Dangling Reference
  c++ 
   Student *c1=new Student();
   Student *c2=c1;
   delete c2;
   c1->getName();

Comments

  1. Just two things:

    System.gc() just asks the Garbage Collector to run but it isn't forced to do so (at least call it a few times will force it for sure).

    The other thing is about finalize(). Yeah the method exists but there are very few situations where you want to use it. For example if you use native resources and you want to be sure they don't leak (even if people missed to explicitly close it) than you could use finalize() as a last way to force resource release.

    ReplyDelete
    Replies
    1. Thanks. Christoph Englbert for Sharing Info.

      Delete

Post a Comment

Popular posts from this blog

Generalization in java with examples

      Generalization basic points  Type/Subtype Relationship  "IS A " Relationship  One class has many subclasses   General class can have many Special classes as  subclasses  General names can be used to Address special names  Top to bottom hierarchy goes towards specialization  Bottom to top Hierarchy goes towards generalization e.g         Soap     Bath Soap and Washing Soap is a subclass of Soap e.g COldDrink   Pepsi      Team -Cold Drink is a general class -Pepsi and team are special classes e.g    Person Teacher       Student e.g            Car     Sedan           Hatchback Honda   Suzuki     Suzuki   Toyota civic        Liana      Alto      vitz ....................................................\ Some Examples from Nature e.g.               Animal            Mammals            Reptiles    Human           Cow     Snake         Croc Student Teacher             Cobra Python     e.g                     Fruits      Mango      

Composition in Java with code examples

Composition  "Have a " Relationship  OR  "Must have" relationship                    between two or more classes. Container class contains component's class object For example a  Car is composed of engine and body. Where Car is a container class and both Engine and Body are components class.  Life Time Issue in Composition Life time of component objects depends on container class If Container object destroyed, component objects will be also destroyed Car Example  There is a composition relationship between car's body and engine. Car must have Engine and body If Car destroyed, both Engine and Body will be destroyed class  Engine {   Engine  () {    System.out.println ( "Engine created" ) ; }   void  start () {    System.out.println ( "Engine Start" ) ;   } } class  Body {   Body  () { System.out.println ( "Body created" ) ; }   void  type () {    System.out.println ( "Sa

Aggregation in java with example codes

What is aggregation?   "Have a" or "May have" relationship  Aggregation is special type of association  Life time of Component object is independent from its  container object E.g A school has one student class  Student  { String name; Student  () { name= null ;  } Student  ( String n ) { name=n;  } void  setName ( String n ) { name=n; } String getName () {  return  name; } } class  School { Student  st; School  (  ) {  st= null ; } School  ( Student s ){ st=s; } void  studentName (){    System.out.println ( st.getName ()) ; } } class  Post { public static  void  main  ( String a []){ Student st= new  Student ( "Imran" ) ; School s=  new  School ( st ) ; s.studentName () ; } } Output Hello Problem : A Car must has Engine and body.           A Car may or may not has Ac Adding Ac as an Aggregate object in car class  Engine { void  start () { System.out.println ( &