Thursday, 17 May 2018

Interesting things to know about Garbage Collection

Garbage Collection is a process to  clean all the unreferenced objects. Garbage Collector call's protected void finalize() method of Object Class before cleaning every garbaged Object to release non-java resources such as file handle or database connection held by that object.


Interesting fact about Garbage Collector:

public class Test
{
    public static void main(String[] args) throws InterruptedException
    {
        String str = new String("Oshin Talreja");
             
     Test test = new Test();
     // making str eligible for gc
        str = null;
test= null;

        // calling garbage collector
        System.gc();
             
        // waiting for gc to complete
        Thread.sleep(1000);
     
        System.out.println("end of main");
    }
    @Override
    protected void finalize()
    {
        System.out.println("finalize method called");
    }
}

OUTPUT:

finalize method called
end of main

Wonder Why Finalize method called once when two object were garbage collected.

Explanation:

Garbage Collector is called for two objects one is String and second is Test. Therefore, finalize() method of String class(if overridden in String class) is called on str. If a class doesn’t override finalize method, then by default Object class finalize() method is called and Object Class Finalize method has an Empty implementation.

Hence, In Output we can read only one call of Finalize method which is for Test object not for String.



For any suggestion or doubts, please comment below :)



Thursday, 5 April 2018

Static Method Override

In reference to my blog  STATIC METHOD CALL FROM NULL REFERENCE This time we have come up with new interesting things about Static method in JAVA.


What will be output??


public class BaseClass {

public static void testStatic(){
System.out.println("In Base Class");
}

}


public class DerivedClass extends BaseClass {
public static void testStatic(){
System.out.println("In Derived Class");
}

}


public class TestClass {

public static void main(String[] args) {
BaseClass base = new DerivedClass();
base.testStatic();
}
}

What will be Output "In Base Class"  or "In Derived Class" ??

OUTPUT: In Base Class 

Wonder!! As I explained in our last blog that Static method is associate with the Class not the Instance of Class so, the base.testStatic will get replaced by BaseClass.testStatic.

 Hence Base class static method will call.

This is the reason why we can't override static method in Derived Class.

For any suggestion or doubts, please comment below :)

Wait, notify and notifyAll method in Object Class

We usually get  surprise  when these methods are present in  Object  class however they only used in  Threading  Concepts.   Wonder WHY?...