Core Java Questions And Answers Part-2

Garbage Collection In Java:
In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.


How can an object be unreferenced?

There are many ways:

è By nulling the reference
è By assigning a reference to another
è By annonymous object etc.

1) By nulling a reference:
Employee e=new Employee(); 
e=null; 

2) By assigning a reference to another:
Employee e1=new Employee(); 
Employee e2=new Employee(); 
e1=e2;//now the first object referred by e1 is available for garbage collection 

3) By annonymous object:
new Employee(); 

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){} 
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc(){} 
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

public class TestGarbage1{ 
 public void finalize(){System.out.println("object is garbage collected");} 
 public static void main(String args[]){ 
  TestGarbage1 s1=new TestGarbage1(); 
  TestGarbage1 s2=new TestGarbage1(); 
  s1=null; 
  s2=null; 
  System.gc(); 
 } 


O/P:  
object is garbage collected
object is garbage collected


Can the Garbage Collection be forced explicitly ?

No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.

Modifiers in Java:
In Java, modifiers are categorized into two types,
Access control modifier
Non Access Modifier

1) Access control modifier: The access modifiers in java specify accessibility (scope) of a data member, method, constructor or class.

Java language has four access modifier to control access levels for classes, variable methods and constructor.

Default : Default has scope only inside the same package
Public : Public scope is visible everywhere
Protected : Protected has scope within the package and all sub classes
Private : Private has scope only within the classes


2) Non-access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties. Non-access modifiers are of 5 types,

Final
Static
Transient
Synchronized
Volatile


What is Exception in Java?
Exception is an error event that can happen during the execution of a program and disrupts it’s normal flow. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.

Whenever any error occurs while executing a java statement, an exception object is created and then JRE tries to find exception handler to handle the exception. If suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then application throws the exception to runtime environment and JRE terminates the program.

What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

è throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.

è throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

è try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.

è finally: finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurrs or not.

Explain Java Exception Hierarchy?

Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.


Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error.

Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions.

Runtime Exceptions are caused by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.





What are important methods of Java Exception Class?

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.

String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use

getMessage() method to return the exception message.
synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.

String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.


void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.


What is difference between Checked and Unchecked Exception in Java?

Checked Exceptions should be handled in the code using try-catch block or else main() method should use throws keyword to let JRE know about these exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.
Exception is the super class of all checked exceptions.
RuntimeException is the super class of all unchecked exceptions.
Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present,

Unchecked exceptions are mostly caused by poor programming, for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.


What is difference between throw and throws keyword in Java?

throws keyword is used with method signature to declare the exceptions that the method might throw

throw keyword is used to disrupt the flow of program and handing over the exception object to runtime to handle it.


How to write custom exception in Java?

We can extend Exception class or any of it’s subclasses to create our custom exception class. The custom exception class can have it’s own variables and methods that we can use to pass error codes or other exception related information to the exception handler.

A simple example of custom exception is shown below.

package com.journaldev.exceptions;

import java.io.IOException;

public class MyException extends IOException {

      private static final long serialVersionUID = 4664456874499611218L;
     
      private String errorCode="Unknown_Exception";
     
      public MyException(String message, String errorCode){
            super(message);
            this.errorCode=errorCode;
      }
     
      public String getErrorCode(){
            return this.errorCode;
      }
}


What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options.


What are different scenarios causing “Exception in thread main”?

Some of the common main thread exception scenarios are:

Exception in thread main java.lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.

Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.

Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have main method.

Exception in thread “main” java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.


What is difference between final, finally and finalize in Java?

final and finally are keywords in java whereas finalize is a method.
final keyword can be used with class variables so that they can’t be reassigned, with class to avoid extending by classes and with methods to avoid overriding by subclasses.

finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources.

finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed.

Out of the three, only finally is related to java exception handling.


What happens when exception is thrown by main method?

When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.


Can we have an empty catch block?

We can have an empty catch block but it’s the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it wil be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.


Provide some Java Exception Handling Best Practices?

Some of the best practices related to Java Exception Handling are:

Use Specific Exceptions for ease of debugging.
Throw Exceptions Early (Fail-Fast) in the program.
Catch Exceptions late in the program, let the caller handle the exception.
Use Java 7 ARM feature to make sure resources are closed or use finally block to close them properly.
Always log exception messages for debugging purposes.
Use multi-catch block for cleaner close.
Use custom exceptions to throw single type of exception from your application API.
Follow naming convention, always end with Exception.
Document the Exceptions Thrown by a method using @throws in javadoc.
Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide null or empty response.


What is difference between Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)


What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.

Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass

does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.


Can we write only try block without catch and finally blocks?

No, It shows compilation error. The try block must be followed by either catch or finally block. You can remove either catch block or finally block but not both.


There are three statements in a try block – statement1, statement2 and statement3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in statement2. Does statement3 get executed or not?

No. Once a try block throws an exception, remaining statements will not be executed. control comes directly to catch block.


What is unreachable catch block error?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e sub classes of Exception must come first and super classes later. If you keep super classes first and sub classes later, compiler will show unreachable catch block error.

public class ExceptionHandling
{
    public static void main(String[] args)
    {
        try
        {
            int i = Integer.parseInt("abc");   //This statement throws NumberFormatException
        }
 
        catch(Exception ex)
        {
            System.out.println("This block handles all exception types");
        }
 
        catch(NumberFormatException ex)
        {
            //Compile time error
            //This block becomes unreachable as
            //exception is already caught by above catch block
        }
    }
}


Can we keep the statements after finally block If the control is returning from the finally block itself?

No, it gives unreachable code error. Because, control is returning from the finally block itself. Compiler will not see the statements after it. That’s why it shows unreachable code error.


Does finally block get executed If either try or catch blocks are returning the control?
Yes, finally block will be always executed no matter whether try or catch blocks are returning the control or not.


Can we throw an exception manually? If yes, how?
Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception manually is
throw InstanceOfThrowableType;
Below example shows how to use throw keyword to throw an exception manually.
try
{
    NumberFormatException ex = new NumberFormatException();    //Creating an object to NumberFormatException explicitly
 
    throw ex;        //throwing NumberFormatException object explicitly using throw keyword
}
catch(NumberFormatException ex)
{
    System.out.println("explicitly thrown NumberFormatException object will be caught here");
}


What is Re-throwing an exception in java?

Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.

try
{
    String s = null;
    System.out.println(s.length());   //This statement throws NullPointerException
}
catch(NullPointerException ex)
{
    System.out.println("NullPointerException is caught here");
 
    throw ex;     //Re-throwing NullPointerException
}


Why it is always recommended that clean up operations like closing the DB resources to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not and raised exceptions are caught in the catch block or not. By keeping the clean up operations in finally block, you will ensure that those operations will be always executed irrespective of whether exception is occurred or not.


Can we override a super class method which is throwing an unchecked exception with checked exception in the sub class?

No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub class with same exception or any other unchecked exceptions but can not be overridden with checked exceptions.


Which class is the super class for all types of errors and exceptions in java?

java.lang.Throwable is the super class for all types of errors and exceptions in java.


What is the use of printStackTrace() method?
printStackTrace() method is used to print the detailed information about the exception occurred.

Give some examples to checked exceptions?

ClassNotFoundException, SQLException, IOException


Give some examples to unchecked exceptions?

NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException


What are chained exception?
In an application, one exception throws many exceptions. i.e one exception causes another exception and that exception causes another exception thus forming chain of exceptions. It is better to know where the actual cause of the exception lies. This is possible with chained exceptions feature of the Java.
Chained exceptions are introduced from JDK 1.4. To implement chained exceptions in java, two new constructors and two new methods are added in the Throwable class. They are,

Constructors Of Throwable class Which support chained exceptions in java :

1) Throwable(Throwable cause)    —-> where cause is the exception that causes the current exception.

2) Throwable(String msg, Throwable cause)   —-> where msg is the exception message and cause is the exception that causes the current exception.


What is StackOverflowError?
StackOverflowError error is thrown by JVM when it encounters that there is no memory left in the stack to store variables . Parameters and local variables are allocated on the stack . The common cause for a stack overflow is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself for ever.


What does 'Ducking' the exception mean?
If a method does not handle the exception but simply declares it using throws , the method is said to be ducking the exception.


What happens when exception is thrown by main method?
When exception is thrown by main , Java runtime system terminates.


What is the concept of multi-catch block ?
In multi-catch block , we can catch multiple exceptions in a single catch block.

Benefits : This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Example :
Without multi catch
catch (IOException ex){
       logger.log(ex);
       throw ex;
}
catch (SQLException ex){
       logger.log(ex);
       throw ex;
}

With multi catch
catch(SQLException | SQLException ex)
{
       logger.log(ex);
       throw ex;
}


Can we have the try block without catch or finally block?
NO . try block must have a catch or finally associated with it.


Can We Overload main() method?
Yes, We can overload main() method. A Java class can have any number of main() methods. But to run the java class, class should have main() method with signature as “public static void main(String[] args)”. If you do any modification to this signature, compilation will be successful. But, you can’t run the java program. You will get run time error as main method not found.

public class MainMethod
{
    public static void main(String[] args)
    {
        System.out.println("Execution starts from this method");
    }

    void main(int args)
    {
        System.out.println("Another main method");
    }

    double main(int i, double d)
    {
        System.out.println("Another main method");

        return d;
}


In case, there is a return at the end of try block, will execute finally block? 
Yes, the finally block will be executed even after writing return statement at the end of try block. 

It returns after executing finally block.


Does system.exit()in try block executes code in finally block? 

try{
System.out.println("I am in try block");
System.exit(1);
} catch(Exception ex){
ex.printStackTrace();
} finally {
System.out.println("I am in finally block!!!");
}



It will not execute finally block. The program will be terminated after System.exit() statement. 


What is the difference between exception and error?
An error is an irrecoverable condition occurring at runtime like out of memory error. These kind of jvm errors cannot be handled at runtime.

Exceptions are because of condition failures, which can be handled easily at runtime.

No comments:

Post a Comment