Thursday, January 24, 2019

Java Exception Handling Interview Questions and Answers

What is Exception in Java?

  1. An exception is an error event that can happen during the execution of a program and disrupts its normal flow. An exception can arise from different kind of situations such as wrong data entered by the 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 an 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 the runtime environment and JRE terminates the program.
    Java Exception handling framework is used to handle runtime errors only, compile-time errors are not handled by the exception handling framework.

Java exception handling interview questions

What is the Exception Handling Keywords in Java?

  1. There are four keywords used in java exception handling.
    1. throw: Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the program. The throws keyword is used to throw an exception to the runtime to handle it.
    2. 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 its caller method using keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
    3. 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.
    4. 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, the block gets executed always, whether an exception occurred or not.

Explain Java Exception Hierarchy?

  1. 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 the 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 a useful message to the 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.

Java exception handling interview questions

What are important methods of Java Exception Class?

  1. Exception and all of its subclasses don’t provide any specific methods and all of the methods are defined in the base class Throwable.
    1. String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception though it’s a constructor.
    2. String getLocalizedMessage() – This method is provided so that subclasses can override it to provide the locale-specific message to the calling program. Throwable class implementation of this method simply uses the method to return the exception message.
    3. synchronized Throwable getCause() – This method returns the cause of the exception or null if the cause is unknown.
    4. String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
    5. 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 the argument to write the stack trace information to the file or stream.

Explain Java 7 ARM Feature and multi-catch block?

  1. If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the features was the multi-catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like below:
    
    catch(IOException | SQLException | Exception ex){
         logger.error(ex);
         throw new MyException(ex.getMessage());
    }
    
    Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So Java 7 one of the improvement was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of the try-catch block, runtime environment automatically closes these resources. Sample of the try-catch block with this improvement is:
    
    try (MyResource mr = new MyResource()) {
                System.out.println("MyResource created in try-with-resources");
            } catch (Exception e) {
                e.printStackTrace();
            }
    

Java exception handling interview questions

What is the difference between Checked and Unchecked Exception in Java?

    1. Checked Exceptions should be handled in the code using try-catch block or else method should use throws keyword to let the caller know about the checked exceptions that might be thrown from the method. Unchecked Exceptions are not required to be handled in the program or to mention them in the throws clause of the method.
    2. Exception is the superclass of all checked exceptions whereas is the superclass of all unchecked exceptions. Note that RuntimeException is the child class of Exception.
    3. Checked exceptions are error scenarios that require to be handled in the code, or else you will get compile time error. For example, if you use FileReader to read a file, it throws and we must catch it in the try-catch block or throw it again to the caller method. 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. For example, I can write a method to remove all the vowels from the string. It’s the caller responsibility to make sure not to pass a null string. I might change the method to handle these scenarios but ideally, the caller should take care of this.

What is the difference between throw and throws keyword in Java?

  1. throws keyword is used with method signature to declare the exceptions that the method might throw whereas 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?

  1. 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 a 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;
     }
     
    
    }
    

Java exception handling interview questions

What is OutOfMemoryError in Java?

  1. 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.
    $>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

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

  1. 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 the main method.
    • Exception in thread “main” java.lang.ArithmeticException: Whenever an exception is thrown from the main method, it prints the exception is console. The first part explains that exception is thrown from the main method, second part prints the exception class name and then after a colon, it prints the exception message.

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

  1. 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 get 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 a 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 an exception is thrown by the main method?

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

Can we have an empty catch block?

  1. 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 will 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?

  1. 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 a multi-catch block for the cleaner close.
    • Use custom exceptions to throw a 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 a null or empty response.

What is the problem with below programs and how do we fix it?

  1. In this section, we will look into some programming questions related to java exceptions.
    1. What is the problem with below program?
      
      package com.journaldev.exceptions;
      
      import java.io.FileNotFoundException;
      import java.io.IOException;
      
      public class TestException {
      
       public static void main(String[] args) {
        try {
         testExceptions();
        } catch (FileNotFoundException | IOException e) {
         e.printStackTrace();
        }
       }
       
       
       
       public static void testExceptions() throws IOException, FileNotFoundException{
        
       }
      }
      
      Above program won’t compile and you will get an error message as “The exception FileNotFoundException is already caught by the alternative IOException”. This is because FileNotFoundException is a subclass of IOException, there are two ways to solve this problem.
      The first way is to use a single catch block for both the exceptions.
      
        try {
         testExceptions();
        }catch(FileNotFoundException e){
         e.printStackTrace();
        }catch (IOException  e) {
         e.printStackTrace();
        }
      
      Another way is to remove the FileNotFoundException from the multi-catch block.
      
        try {
         testExceptions();
        }catch (IOException  e) {
         e.printStackTrace();
        }
      
      You can choose any of these approach based on your catch block code.
    2. What is the problem with below program?
      
      package com.journaldev.exceptions;
      
      import java.io.FileNotFoundException;
      import java.io.IOException;
      
      import javax.xml.bind.JAXBException;
      
      public class TestException1 {
      
       public static void main(String[] args) {
         try {
          go();
         } catch (IOException e) {
          e.printStackTrace();
         } catch (FileNotFoundException e) {
          e.printStackTrace();
         } catch (JAXBException e) {
          e.printStackTrace();
         }
       }
      
       public static void go() throws IOException, JAXBException, FileNotFoundException{
        
       }
      }
      
      The program won’t compile because FileNotFoundException is a subclass of IOException, so the catch block of FileNotFoundException is unreachable and you will get an error message as “Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException”.
      You need to fix the catch block order to solve this issue.
      
         try {
          go();
         } catch (FileNotFoundException e) {
          e.printStackTrace();
         } catch (IOException e) {
          e.printStackTrace();
         } catch (JAXBException e) {
          e.printStackTrace();
         }
      
      Notice that JAXBException is not related to IOException or FileNotFoundException and can be put anywhere in above catch block hierarchy.
    3. What is the problem with the below program?
      
      package com.journaldev.exceptions;
      
      import java.io.IOException;
      
      import javax.xml.bind.JAXBException;
      
      public class TestException2 {
      
       public static void main(String[] args) {
        try {
         foo();
        } catch (IOException e) {
         e.printStackTrace();
        }catch(JAXBException e){
         e.printStackTrace();
        }catch(NullPointerException e){
         e.printStackTrace();
        }catch(Exception e){
         e.printStackTrace();
        }
       }
      
       public static void foo() throws IOException{
        
       }
      }
      
      The program won’t compile because JAXBException is a checked exception and foo() method should throw this exception to catch in the calling method. You will get an error message as “Unreachable catch block for JAXBException. This exception is never thrown from the try statement body”.To solve this issue, you will have to remove the catch block of JAXBException.Notice that catching NullPointerException is valid because it’s an unchecked exception.
    4. What is the problem with below program?
      
      package com.journaldev.exceptions;
      
      public class TestException3 {
      
       public static void main(String[] args) {
        try{
        bar();
        }catch(NullPointerException e){
         e.printStackTrace();
        }catch(Exception e){
         e.printStackTrace();
        }
        
        foo();
       }
      
       public static void bar(){
        
       }
       
       public static void foo() throws NullPointerException{
        
       }
      }
      
      This is a trick question, there is no problem with the code and it will compile successfully. We can always catch Exception or any unchecked exception even if it’s not in the throws clause of the method.
      Similarly, if a method (foo) declares the unchecked exception in the throws clause, it is not mandatory to handle that in the program.
    5. What is the problem with below program?
      
      package com.journaldev.exceptions;
      
      import java.io.IOException;
      
      public class TestException4 {
      
       public void start() throws IOException{  
       }
       
       public void foo() throws NullPointerException{
        
       }
      }
      
      class TestException5 extends TestException4{
       
       public void start() throws Exception{
       }
       
       public void foo() throws RuntimeException{
        
       }
      }
      
      The above program won’t compile because the start() method signature is not the same in a subclass. To fix this issue, we can either change the method signature in the subclass to be exactly the same as the superclass or we can remove the throws clause from the subclass method as shown below.
      
      @Override
       public void start(){
       }
      
    6. What is the problem with below program?
      
      package com.journaldev.exceptions;
      
      import java.io.IOException;
      
      import javax.xml.bind.JAXBException;
      
      public class TestException6 {
      
       public static void main(String[] args) {
        try {
         foo();
        } catch (IOException | JAXBException e) {
         e = new Exception("");
         e.printStackTrace();
        }catch(Exception e){
         e = new Exception("");
         e.printStackTrace();
        }
       }
      
       public static void foo() throws IOException, JAXBException{
        
       }
      }
      
      The above program won’t compile because exception object in the multi-catch block is final and we can’t change its value. You will get the compile-time error as “The parameter e of a multi-catch block cannot be assigned”.

Java IO Streams Interview Questions and Answers

Java IO Streams Interview Questions and Answers 

  1. What is an IO stream?
    It is a stream of data that flows from source to destination. A good example is file copying. Two streams are involved – input stream and output stream. An input stream reads from the file and stores the data in the process (generally in a temporary variable). The output stream reads from the process and writes to the destination file.
  2. What is the necessity of two types of streams – byte streams and character streams?
    Byte streams were introduced with JDK 1.0 and operate on the files containing ASCII characters. We know Java supports other language characters also known as Unicode characters. To read the files containing Unicode characters, the designers introduced character streams with JDK 1.1. As ASCII is a subset of Unicode, for the files of English characters, we can go with either byte streams or character streams.
  3. What are the super most classes of all streams?
    All the byte stream classes can be divided into two categories (input stream classes and output stream classes) and all character streams classes into two (reader classes and writer classes). There are four abstract classes from which all these streams are derived. The super most class of all byte stream classes is java.io.InputStream and for all output stream classes, java.io.OutputStream. Similarly for all reader classes is java.io.Reader and for all writer classes are java.io.Writer.
  1. What are FileInputStream and FileOutputStream?
    These two are general purpose classes used by the programmer very often to copy the file to file. These classes work well with files containing fewer data of a few thousand bytes as by performance these are very poor. For larger data, it is preferred to use BufferedInputStream (or BufferedReader) and BufferedOutputStream (or BufferedWriter).
  2. Which you feel better to use – byte streams or character streams?
    I feel personal to go with character streams as they are the latest. Many features exist in character streams that do not in byte streams like a) using BufferedReader in place of BufferedInputStreams and DataInputStream (one stream for two) and b) using newLine()method to go for next line and for this effect we must go for extra coding in byte streams etc.
  3. What System.out.println()?
    "println()" is a method of PrintStream class. "out" is a static object of PrintStream class defined in "System" class. The system is a class from java.lang package used to interact with the underlying operating system by the program.
  4. What are the filter streams?
    Filter streams are a category of IO streams whose responsibility is to add extra functionality (advantage) to the existing streams like giving line numbers in the destination file that do not exist in the source file or increasing performance of copying etc.
  5. Name the filter streams available?
    There are four filter streams in the java.io package – two on the byte streams side and two in the character streams side. They are FilterInputStreamFilterOutputStreamFilterReader and FilterWriter. These classes are abstract classes and you cannot create objects of these classes.
  6. Name the filter stream classes on the reading side of byte stream?
    There are four classes – LineNumberInputStream (the extra functionality is it adds line numbers in the destination file), DataInputStream (contains special methods like readInt(), readDouble() and readLine() etc that can read an int, a double and a string at a time), BufferedInputStream (gives buffering effect that increases the performance to the peak) and PushbackInputStream (pushes the required character back to the system).
  7. .Java IO Streams Interview Questions and Answers 
  8. What is the functionality of SequenceInputStream?
    It is very useful to copy multiple source files into one destination file with very less code.
  9. What are PrintStream and PrintWriter?
    Functionally both are the same but belong to two different categories – byte streams and character streams. println() method exists in both classes.
  10. Which streams are advised to use to have maximum performance in file copying?
    BufferedInputStream and BufferedOutputStream on byte streams side and BufferedReader and BufferedWriter on character streams side.
  11. What are piped streams?
    There are four piped streams – PipedInputStream, PipedOutputStream, PipedReader, and PipedWriter. These streams are very useful to pass data between two running threads (say, processes). Java IO Interview Questions and Answers
  12. What is File class?
    It is a non-stream (not used for file operations) class used to know the properties of a file like when it was created (or modified), has read and write permissions, size, etc.
  13. What is RandomAccessFile?
    It is a special class from the java.io package which is neither an input stream nor an output stream (because it can do both). It is directly a subclass of Object class. Generally, a stream does only one purpose of either reading or writing: but RandomAccessFile can do both readings from a file and writing to a file. All the methods of DataInputStream and DataOutStream exist in RandomAccessFile.

Java Constructor Interview Questions and Answers

Java Constructor Interview Questions and Answers

1. What is a Constructor in Java?

Constructor is just like a method in Java that is used to initialize the state of an object and will be invoked during the time of object creation.

2. What are the Rules for defining a constructor?

  1. Constructor name should be the same as the class name.
  2. It cannot contain any return type.
  3. It can have all Access Modifiers are allowed (private , public, protected, default).
  4. It Cannot have any Non Access Modifiers (final ,static, abstract, synchronized).
  5. No return statement is allowed.
  6. It can take any number of parameters.
  7. Constructor can throw exception, we can have throws clause.

3. What is the use of Private Constructors in Java?

When we use private for a constructor then object for the class can only be created internally within the class, no outside class can create object for this class. Using this we can restrict the caller from creating objects.
class PrivateConstructorExample
{
    /**
     * Private Constructor for preventing object creation
    from outside class
    **/
    private PrivateConstructorExample(){ }
    
    public void disp()
    {
        System.out.println("disp() method called");
    }
}
public class Sample 
{
    public static void main(String args[])
    {
        //Creating the object for the Private Constructor class
        PrivateConstructorExample pc = new PrivateConstructorExample();
        
        pc.disp();
    }
}
When we run the above code we will be getting the below exception.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The constructor PrivateConstructorExample() is not visible

 at Sample.main(Sample.java:19)

4. Can we have a Constructor in an Interface?

No, We cannot have a Constructor defined in an Interface.

Java Constructor Interview Questions

5. What is Constructor Chaining in Java?

Constructor Chaining is nothing but calling one Constructor from another. this keyword is used to call the current class constructor and super keyword is used to call the parent class constructor.
class Parent
{
    public Parent()
    {
        System.out.println("Parent class no-args constructor called");
    }
    public Parent(String name)
    {
        System.out.println("Parent class Parameterized constructor called by "+name);
    }
}
public class Child extends Parent
{
    public Child()
    {
        this("JIP");
        System.out.println("Child class no-args constructor called");
    }
    public Child(String name)
    {
        super("JIP");
        System.out.println("Child class Parameterized constructor called by "+name);
    }
    public static void main(String args[])
    {
        Child c = new Child();
    }
}
Output :
Parent class Parameterized constructor called by JIP
Child class Parameterized constructor called by JIP
Child class no-args constructor called

6. Can we have this and super in the same constructor?

No, we cannot have have this and super in a same constructor as anyone only can be in the first line of the constructor.
class Parent
{
    public Parent()
    {
        System.out.println("Parent class no-args constructor");
    }
}
public class Child extends Parent
{
    public Child()
    {
        this("JIP");
        super();
        System.out.println("Child class no-args constructor");
    }
    public Child(String name)
    {
        
        System.out.println("Child class Parameterized constructor"+name);
    }
    public static void main(String args[])
    {
        Child c = new Child();
    }
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Constructor call must be the first statement in a constructor

 at Child.(Child.java:13)
 at Child.main(Child.java:23)


7. Is it possible to call a subclass constructor from the superclass constructor?

No. You cannot call a subclass constructor from a superclass constructor.

8. What is a No-arg constructor?

Constructor without arguments is called no-arg constructor. In Java Default constructor is a no-arg constructor.
class Demo
{
    public Demo()
    {
        //No-arg constructor
    }
}

9. Can we have a class with no Constructor in it ? What will happen during object creation ?

Yes, we can have a class with no constructor, When the compiler encounters a class with no constructor then it will automatically create a default constructor for you.

10. Can we have both Default Constructor and Parameterized Constructor in the same class?

Yes, we have both Default Constructor and Parameterized Constructor in the same class.

11. Can a Constructor return any value?

A Constructor cannot return any explicit value but implicitly it will be returning the instance of the class.

12. Will compiler create the Default Constructor when we already have a Constructor defined in the class ?

No, the compiler will not create the Default Constructor when we already have a Constructor defined.

Java Constructor Interview Questions

13. Can an abstract class in Java have a constructor?

Yes, an abstract class can have a constructor. The below code works perfectly fine.
abstract class Demo1 { 
    String value;
    public Demo1( String value ) {
        this.value = value;
    }
    public String getValue()
    {
     return value;
    }
}
public class Test extends Demo1 {
    public Test() {
        super("CoreJava");
    }
}

14. What happens when a Constructor is defined as “protected”?

In general protected method can be accessed by other class in a different package only through Inheritance. But when you assign protected access to a constructor it behaves a bit different. It can be accessed only by a call of super() (according to JLS) and not directly by any other means.
package com.javainterviewpoint;

public class Parent
{
    protected Parent()
    {
        System.out.println("Parent Constructor called");
    }
    public void parentDisp()
    {
        System.out.println("Parent Disp called");
    }
}
package com.javainterviewpoint1;

import com.javainterviewpoint.Parent;

public class Child extends Parent
{
    public Child()
    {
        /**
         * Using super() Parent Class protected constructor can be called
         */
        super(); 
        System.out.println("Child Constructor called");
    }
    public void childDisp()
    {
        System.out.println("Child Disp called");
    }
    public static void main(String args[])
    {
        /**
         * Even though we have extended Parent class in Child class, 
         * below way of calling Parent class Constructor is not allowed
         * 
         * The constructor Parent() is not visible - error will be thrown
         */
        Parent p = new Parent() // Error will be thrown
    }
}

15. Why constructors cannot be final in Java?

When you set a method as final, then” The method cannot be overridden by any class”, but Constructor by JLS ( Java Language Specification ) definition can’t be overridden. A constructor is not inherited, so there is no need for declaring it as final.

16. Why constructors cannot be abstract in Java?

When you set a method as abstract, then “The method doesn’t or cannot have body”. A constructor will be automatically called when object is created. It cannot lack a body moreover an abstract constructor could never be implemented.

17. Why constructors cannot be static in Java?

When you set a method as static, it means “The Method belong to class and not to any particular object” but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static.

Java String Interview Questions and Answers

1) What is String in Java? Is String is data type? String in Java is not a primitive data type like int, long or double. The string is a ...