Using static block and finalizer together?

Given the given code, print the output as Dear Rohit, Welcome to India without changing anything inside main()
import static java.lang.System.out;
public class Sample 
{
    public static void main(String[] args) 
    {
        out.print("Welcome");
    }
}

Solution

import static java.lang.System.out;
public class Sample
{
    public void finalize()
    {
        out.print(" to India");
    }
    static
    {
        out.print("Dear Rohit, ");
        Sample x=new Sample();
        x=null;
        System.gc();
    }
    public static void main(String[] args)
    {
        out.print("Welcome");
    }
}



Comments