Core Java questions for Computer Science and MCA students

What is Garbage Collection?

  • Garbage collection is also called as an automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.
  • The purpose of garbage collection is to identify and remove the objects that are no longer needed by a program.
  • A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
  • Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.
  • By calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects.
  • There is no guarantee that the garbage collection will start immediately upon request of System.gc().
Advantage of garbage collection
  • The java memory becomes more efficient as the garbage collector removes the unreferenced objects from the heap memory.
  • No extra efforts are needed as the garbage collector works automatically.
Example
public class gar1
{
     public void finalize()
     {
          System.out.println("garbage collection");
     }
     public static void main(string args[])
     {
          gar1 a1 = new gar1();
          gar1 a2 = new gar1();
          a1 = null;
          a2 = null;
          System.gc();
     }
}

What is difference between Abstract and Final keyword?

  • Both the keywords 'abstract' and 'final' are complementary to each other.
  • A class cannot be inherited if a class is declared with the final keyword.
  • To define the abstract methods the abstract class has to be inherited.
  • The final keyword cannot be used with an abstract class.
  • A constructor cannot be abstract. They however can be declared in an abstract class but cannot be called.
  • The constructor that belongs to the abstract parent class can be invoked by using the super keyword inside the constructor of the child class that can be invoked.
Example
abstract class a
{
     public abstract void test();
     a()
     {
          System.out.println("a constructor");
     }
}
class b extends a
{
     Public void test()
     {
          System.out.print("Hi");
     }
     b()
     {
          Super();
     }
}
class example
{
     public static void main(String args[])
     {
          a x = new b();
          x.test();
     }
}

Explain types of exception with example.

Java basically has three types of exceptions. They are as follows:

1. Checked exceptions
This type of exception is generally a user error or an error which the programmer cannot ignore. It generally uses the throw and throws keyword for exception handling. They are the subclass of Exception excluding the Error its child class and RuntimeException and its child class.

Example:
public class check
{
     void see()
     {
          try
          {
               throw new Exception();
          }
          catch (Exception e)
          {
               System.out.println("Hi");
          }
     }
     void dis () throws Exception
     {
          throw new Exception();
     }
     public static void main (String args[])
     {
          checked a = new checked();
          a.show();
          try
          {
               a.display();
          }
          catch (Throwable t)
          {
               System.out.println("interface");
          }
     }
}

2. Unchecked exceptions
They are also called as the RuntimeException. These exceptions can be avoided by the developer. They are even ignored during runtime.

Types of unchecked exceptions
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ClassCastException
  • ClassCastException
  • IllegalArgumentException
  • IllegalMonitorStateException
  • IllegalStateException
  • IllegalThreadStateException
  • IndexOutOfBoundsException
  • NegativeArraySizeException
  • NullPointerException
  • NumberFormatException
  • SecurityException
  • StringIndexOutOfBoundsException
  • UnsupportedOperationException
  • ClassNotFoundException
  • CloneNotSupportedException
  • IllegalAccessException
  • InstantiationException
  • NoSuchFieldException
  • NoSuchMethodException
Example
public class uncheck
{
     public void see()
     {
          try
          {
               throw new Error();
          }
          catch (Exception e)
          {
               System.out.println("Hi");
          }
     }
     void dis ()
     {
          throw new Error();
     }
     public static void main (String args[])
     {
          uncheck a = new uncheck();
          a.show();
          try
          {
               a.display();
          }
          catch (Throwable t)
          {
               System.out.println("interface");
          }
     }
}

3. Chained Exception
An application responds to an exception by throwing an exception. The first exception causes the second exception it is known as a chained exception. It takes time to respond to an exception by throwing another exception i.e the first exception causes the second exception.

Example
import java.io.*;
class Myexcept extends Exception
{
     Myexcept(String message)
     {
          Super(message);
     }
}
public class ChainExcept
{
     public static void main (String args[]) throws MyExcept,IOException
     {
          try
          {
               int rs = 10/0;
          }
          catch (Exception e)
          {
               System.out.println (e.getMessage());
               System.out.println (e.getCause());
               throw new MyExcept("Chained ArithmeticException");
          }
     }
}

Explain finalize().

  • The Finalize method of an object is called when GC(Garbage Collector) is about to cleanup the object.
  • We can keep cleanup code in the finalize block.
  • It is the last chance for any object to perform the cleanup activity.
  • Finalize method is defined in 'java.lang.Object' class.
  • Any exception is thrown by finalize method.
  • The 'System.runFinalization()' and 'Runtime.getRuntime().runFinalization' methods increases the probability of finalize method.
Declaration of Finalize()

protected void finalize()

Example:
package com.careerride;
import java.util.*;
public class Demo extends GregorianCal
{
     public static void main(String[] args)
     {
          try
          {
               // creating a new Demo object
               Demo c = new Demo();
               // printing the current time
               System.out.println("" + c.getTime());
               // the finalize call
               System.out.println("Final....");
               c.finalize();
               System.out.println("Finalized");
          }
          catch (Throwable t)
          {
               t.printStackTrace();
          }
     }
}

What is Object Serialization?

  • Serialization is the process of saving the state of object to a byte stream. This enables us to save the state of object. So that we can use this value to again restart our program using Deserialization Process. This value can be stored in file.
  • Serialization allows the objects to move from one computer to another by maintaining their state.
  • It implements java.io.Serialization interface with few lines of code.
The following is the class declaration to serialize an object Public class UserData implements java.io.Serializable:
  • When an application uses objects, it cannot use all objects at once.
  • The required objects can be desterilized and then it handles.
  • Later another object is handled, allowing the memory to conserved space for better performance.