Top 20 Java Interview Questions and Answers.

Top 20 Java Interview Questions and Answers.


Top 20 Java Interview Questions and Answers. Frequently asked core Java Interview Questions and Answers for freshers and experienced.

List of Top Java Interview Questions and Answers for freshers and experienced.

Top 25 Java Concurrency Interview Questions Answers for Freshers and Experienced.


Question 1. What are Threads in Java?

In Java, when a program requires more than one task to execute in parallel, say for example,
  1. Reading a data from a local file.
  2. Reading a data from remote connection.
When both of above task need to be executed in parallel at that time Threading will come in picture.
So Java Threads helps creating multiple independent path of execution within a program which can run parallely.  


Question 2. How many ways Threads can be created in java?

There is only one way by which a Thread can be created in java using java.lang.Thread class as shown below,
Thread thread1 = new Thread();
 
After creating a Thread object, a separate independent path is created but what task this independent path will execute? How many ways are there to assign task to a thread?
There are mainly 3 ways by which Task can be assigned to a Thread either by,
  1. java.lang.Runnable 
  2. java.lang.Thread class itself.
  3. java.util.concurrent.Callable Interface.
Let's see complete example of creating a Thread and assigning task to it using,

1. Runnable interface.

class ThreadDemo{
 public static void main(String[] args) {
  
  //Lets create Task first to assign it to the Thread
  ThreadTask threadTask = new ThreadTask();
  
  //Lets create a Thread and assign task to it.
  //Way to assign task to a Thread is by passing task object(Runnable) to Thread's constructor.
  Thread thread1 = new Thread(threadTask);
  
  //Start a thread
  thread1.start();
 }
}

class ThreadTask implements Runnable{
    @Override
    public void run() {
     //Code present here will be executed in separate independent path.
    }
}
2. Thread class
class ThreadDemo extends Thread{
 
 @Override
 public void run() {
   //Code present here will be executed in separate independent path.
 }
 
 public static void main(String[] args) {
  
  //Lets create Task first to assign it to the Thread
  ThreadDemo threadTask = new ThreadDemo();
  
  //Lets create a Thread and assign task to it.
  //Way to assign task to a Thread is by passing task object(Runnable) to Thread's constructor.
  Thread thread1 = new Thread(threadTask);
  
  //Start a thread
  thread1.start();
 }
}

3. Callable interface
class ThreadDemo{
 public static void main(String[] args) {
  
  //Create a Thread Pool of size 2 (2 here is number of threads in Thread pool.)
  ExecutorService executorService = Executors.newFixedThreadPool(2);
  //After creating a pool, it internally starts a Thread, so no need to explicitly start a thread as we did in other approach.
  //Remember only Threads are started but what task they will execute that will be passed to thread using submit() method.
  //In this approach threads will be created and started but they will wait for task to be assigned to them.     
  
  //Create Task to assign it to Threads present in Thread pool.
  ThreadTask threadTask = new ThreadTask();
  
  //Submit a task to Threads present in Thread pool. 
  Future<Result> resultObject = executorService.submit(threadTask);
  //Once a task is submitted to submit method, one of the Thread from the pool will pick the task and execute run method of task.
  //Wait for the result Object(resultObject) that will be returned by Thread after task execution.
  
  Result result = null;
  try {
   //get method will be blocked until the Thread doesn't complete it work and return a result
   result = resultObject.get();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } catch (ExecutionException e) {
   e.printStackTrace();
  }
  
  System.out.println(result.code + " " + result.message);
  executorService.shutdown();
 }
}
class ThreadTask implements Callable<Result> {
 
 //method where the thread execution takes place
 public Result call() {
  //Code present here will be executed in separate independent path.   
  Result response = new Result();
  response.code = 200;
  response.message = "SUCCESS";
  return response;
 }
 
}
class Result{
 public int code;
 public String message;
}
   
So to summarize the answer, There is 1 way to create a Thread but task can be assigned to Thread using 3 different ways either by using.
  1. Runnable interface (run() method will be invoked)
  2. Thread class (run() method will be invoked)
  3. Callable interface (call() method will be invoked)


Question 3.
For starting a Thread we call thread.start() which internally invokes run() method. What if we call run() method directly without using start() method ?

To answer this question one should know the purpose of start method and how Threading works internally.

When a start() method is invoked, it internally invokes start0, which is a native method call.
private native void start0();
The basic purpose of start() method is to instruct running Operating System to create a new Thread which can be executed independently of Thread created it.

when start() method is invoked, Thread will be created and it executes run() method of Task submitted.

By calling thread.run() directly, will not create a new Thread instead it will call run method of the task submitted on the same caller thread.
So there will be no separate execution for newly created Thread.


Question 4. Can we Start a thread twice ?

No. Thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.
thread.start() can be called only once.
class ThreadDemo{
 public static void main(String[] args) {
  
  Thread thread1 = new Thread(new Runnable() {
   public void run() {
    System.out.println("Inside run.");
   }
  });
  thread1.start();
  thread1.start();
 }
}

Output: Inside run. Exception in thread "main" java.lang.IllegalThreadStateException 

How it throws IllegalThreadStateException?
If you see the code of start() method, you will observe that Thread maintains threadStatus whose value initialy is 0 and once the thread is completed its value is 2.
 private volatile int threadStatus = 0;
 public synchronized void start() {
       
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        }
        ....
        ....    
}
So when thread.start() is called again, threadStatus value is 2 and not 0 that is why it throws IllegalThreadStateException .




Question 5.
Can main thread dies before the child thread?
Does child threads still executes even after if their parent thread dies or terminates?
Will JVM exits after main thread is dead?

First of all I would like to tell you that there is no concept of parent - child relationship between threads.
Each and every thread created is independent of thread who created it.

Now coming back to actual question, Can main Thread dies before the child thread? Yes. 
Main thread dies after completing its job even after the thread created by main thread is not yet completed.

But point is will JVM die or not. 
If there exist any non-daemon thread in JVM which is not yet completed then JVM will not exit and wait until all no non-daemon threads completes its task.
In other words, we can also say, JVM will exit when the only running threads are daemon threads.

Lets see example below and things will be more clear,
public class ThreadDemo {
 public static void main(String ar[]){

  final Thread mainThread = Thread.currentThread();
  System.out.println("Inside Main Thread :"+mainThread.getName());

  new Thread(new Runnable() {

   @Override
   public void run() {
    Thread childThread= Thread.currentThread();
    for(int i=0; i<5;i++){
     System.out.println("Inside Child Thread :"+childThread.getName());
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    System.out.println("Check Main Thread is alive :" + mainThread.isAlive());
   }

  }).start();

  System.out.println("End of Main Thread");  
 }
}



Question 6.
Is there any relationship between threads like parent-child?

No. Thre is no relationship between Threads like parent or child thread. Once thread is created it is totaly separate independent thread from the thread who created it. 

There is no relationship between Thread newly created and Thread who created it except for Thread priority and Daemon property.

Thread priority and Daemon property of Thread is copied to the newly created thread from the thread created it.

To put it in simple terms, When you start a thread it inherits the,
  1. Thread daemon property and 
  2. Thread priority
from the "parent" thread to "child" thread and that is the only relationship between threads and no other relation exist after thread starts.

Lets see with simple example,

public class ThreadDemo{
 
 public static void main(String ar[]){
  System.out.println("Inside Main Thread");
  
  Thread thread = new Thread(new ThreadTask());
  thread.setDaemon(true);
  thread.start();
  
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("End of Main Thread");  
 }
}
class ThreadTask implements Runnable{

 @Override
 public void run() {
  System.out.println("Inside Thread Task start");
  
  new Thread(new Runnable() {
   
   public void run() {
    Thread childThread = Thread.currentThread();
    while(true){
     System.out.println("Inside Child Thread :"+childThread.getName());
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }

  }).start();
  
  System.out.println("Inside Thread Task end");
 }
 
}


Output:
Inside Main Thread
Inside Thread Task start
Inside Thread Task end
Inside Child Thread :Thread-1
Inside Child Thread :Thread-1
Inside Child Thread :Thread-1
Inside Child Thread :Thread-1
Inside Child Thread :Thread-1
End of Main Thread


After main thread completed, JVM terminates even if there was 2 threads present one was Daemon thread and other thread inherited Daemon property from thread created it. 




Question 7.
What is the use of join method in case of threading in java?

join() method is used for waiting the thread in execution until the thread on which join is called is not completed.
Remember, the thread which will wait is the thread in execution and it will wait until the thread on which join method called is not completed.

Lets take a scenario, we have Main thread, Thread 1, Thread 2 and Thread 3 and we want our thread to execute in particular scenario like,
Main thread to start first and ends only after all 3 threads is completed.
Thread 1 to start and complete.
Thread 2 to start only after Thread 1 is completed.
Thread 3 to start only after Thread 2 is completed.

Let's see program for it.
public class ThreadDemo {
 
 public static void main(String ar[]){
  System.out.println("Inside Main Thread");
  
  Thread thread1 = new Thread(new ThreadTask());
  thread1.start();
  
  Thread thread2 = new Thread(new ThreadTask(thread1));
  thread2.start();
  
  Thread thread3 = new Thread(new ThreadTask(thread2));
  thread3.start();
   
  try {
   thread1.join();
   thread2.join();
   thread3.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("End of Main Thread");  
 }
}
class ThreadTask implements Runnable{

 public ThreadTask() {}
 
 public ThreadTask(Thread threadToJoin) {
  try {
   threadToJoin.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 @Override
 public void run() {
  System.out.println("Start Thread :"+Thread.currentThread().getName());  
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("End Thread :"+Thread.currentThread().getName());
 } 
}

Output:
Inside Main Thread
Start Thread :Thread-0
End Thread :Thread-0
Start Thread :Thread-1
End Thread :Thread-1
Start Thread :Thread-2
End Thread :Thread-2
End of Main Thread



Question 8.
Can Thread be created without any ThreadGroup, I mean can Thread exist independently without associated to any ThreadGroup?

No. Thread cannot be created independently, it will be part of atleast one of the Thread Group.

Generally, while creating Thread we do not associate it to any Thread Group, but internally it will be part of "main" Thread Group.

So let's see how ThreadGroup hierarchical structure is, 
Threads / Thread Groups, which are directly created within main thread will be part of "main" thread group and will be parallel to main thread.

What will be output of below lines?
public static void main(String[] args) {
 System.out.println("Top Level Thread Group:" + Thread.currentThread().getThreadGroup().getParent().getName());
 System.out.println("Main Thread Group:" + Thread.currentThread().getThreadGroup().getName());
}
Output:Top Level Thread Group: system
Main Thread Group: main


Question 9.
When join method is invoked, does thread release its resources and goes in waiting state or it keep resources and goes in waiting state?

If you look at source code of join() method, It internally invokes wait() method and wait() method release all the resources before going to WAITING state.
public final synchronized void join(){
    ...
    while (isAlive()) {
        wait(0);
    }
    ...
}
So, YES. join() method release resources and goes to waiting state.

Let's see sample program and understand,
class ThreadJoinDemo extends Thread{
 static ThreadJoinDemo thread1;

 public void run(){
  try{
   synchronized(thread1){
    System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1");
    Thread.sleep(5000);
    System.out.println(Thread.currentThread().getName()+" completed");
   }
  }
  catch (InterruptedException e){ }
 }

 public static void main(String[] ar) throws Exception{
  thread1 = new ThreadJoinDemo();
  thread1.setName("thread1");
  thread1.start();

  synchronized(thread1){
   System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1");
   Thread.sleep(1000);
   thread1.join();
   System.out.println(Thread.currentThread().getName()+" completed");
  }
 }
}


  1. If you see the code, "main" thread took a lock on Thread "thread1" and waits for thread1 to complete its task by calling thread1.join().
  2. Thread "thread1", require a lock on "thread1" for executing its task.
    If main thread doesn't release lock by calling thread1.join() then Thread "thread1" will not able to progress and goes in deadlock state.
More Questions on Multithreading....... here

Top 5 Interface Interview Questions Answers.


Question 1. Super class of all classes is java.lang.Object class, does this applies to Interface as well? What is super class of all Interface in Java?

java.lang.Object class is the super class of all Java classes. All non-primitive types (including arrays) inherit either directly or indirectly from Object class. 
For Interface that is not the case, Super class of Interface is null.

From below program that will be clear.

interface ITest{}
class CTest{}

class Test{ 
 public static void main(String[] args) {
  System.out.println(CTest.class.getSuperclass()); // class java.lang.Object
  System.out.println(int[].class.getSuperclass()); // class java.lang.Object
  System.out.println(ITest.class.getSuperclass()); // null
  System.out.println(int.class.getSuperclass());   // null
 }
}
Output:
 class java.lang.Object
 class java.lang.Object
 null
 null


Question 2. Can Interface access methods of Object class? What is the output of below program? Will it compile and run properly?

java.lang.Object class is the super class of all Java classes. All non-primitive types (including arrays) inherit either directly or indirectly from Object class. 
For Interface that is not the case, Super class of Interface is null.
interface ITest{
 String abc();
}
class CTest implements ITest{
 @Override
 public String abc() {
  return "hello";
 }
}

class Test{ 
 public static void main(String[] args) {
  ITest i = new CTest();
  System.out.println(i.abc());
  System.out.println(i.toString());
 }
}
Output:
hello
com.javabypatel.sample.test.dto.CTest@4e44ac6a
 

Call to i.abc() is fine but call to i.toString() method should work or should not work as 
toString() method is not declared in interface ITest.

Yes. It should work because all the public methods of Object class are accessible through interface object.

Note: Interface doesn't extends Object class by default.

Every Interface (that doesn't explicitly extend another interface) has an implicit method declaration for each public method in Object class thats is why you can see all the Object class methods accessible on "i" in above program.

Details:
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.


Question 3. What access specifier are allowed for methods in Interface?

Only public and abstract are allowed as access specifier for methods. Also if method is not declared any access specifier then public and abstract are by default added to methods declared in interface.
interface ITest{
 protected String abc(); // Compile Error
}


Question 4. What access specifier are allowed for variables in Interface?

Only public, static and final are allowed for variables declared in interface. Also if variable is not declared with any access specifier then by default public, static and final is added to variables declared in interface.
interface ITest{
 protected int a; // Compile Error
}


Question 5. What is the output of below program? Is it valid overriding of method test() of interface ITest?

interface ITest{
 Object test(Object o) throws IOException;
}

class CTest implements ITest{
 @Override
 public synchronized String test(Object o) throws IOException, FileNotFoundException, EOFException, 
            StackOverflowError, IndexOutOfBoundsException{
  return "hello";
 }
}
Yes. It is perfectly valid method overriding. 
  1. Access specifier of method cannot be changed which is public in class CTest and is valid.
  2. Adding or removing synchronized keyword doesn't take part in overriding as it is upto implementer whether they want several threads to allow method execution simultaneously or one after another. So it is valid.
  3. Return type should be same or compatible(belong from hierarchy). String(all class) by default extends Object, so belongs from hierarchy and is valid.
  4. Name of method should be exactly same and it is valid.
  5. Parameter should be exactly same and it is valid.
    Note: Compatible parameters that is parameter from same hierarchy tree is Invalid and it should be exactly same.(In our case, decaring parameter as String for test() in CTest is invalid).
  6. For Exception, If overriding method choose not to throw any Exception is perfectly valid even if overriden method in interface is throwing.
    So in our case if overriding test() method choose not to throw any Exception then also it is perfectly valid.
    If it throws then it should be same or any number of compatible exceptions.
    Runtime exception will not take part in overriding, it is upto overriding method to throw or not to throw Runtime exception.


More Questions on Interface here

Top 5 Type Casting Interview Questions Answers.


Question 1. We have a requirement to display all the features of a Bird and a class is designed as shown below, how to display all the features of each Bird?

interface Bird{
 void walk();
}

interface Fly{
 void fly();
}

interface Swim{
 void swim();
}

class Duck implements Bird, Fly, Swim{
 @Override
 public void swim() {
  System.out.println("Duck.swim()");
 }

 @Override
 public void fly() {
  System.out.println("Duck.fly()");
 }

 @Override
 public void walk() {
  System.out.println("Duck.walk()");
 }
}

class Pigeon implements Bird, Fly{
 @Override
 public void fly() {
  System.out.println("Pigeon.fly()");
 }

 @Override
 public void walk() {
  System.out.println("Pigeon.walk()");
 }
}

For displaying all the features of Pigeon and Duck, we only need to know what all operations Birds can support like Fly, Swim etc? Based on type checking, we can call particular operation and display all features.
class Zoo{
 public static void main(String[] args) {
  
  Bird bird1 = new Duck();
  bird1.walk();
  if(bird1 instanceof Fly){
   ((Fly)bird1).fly();
  }
  if(bird1 instanceof Swim){
   ((Swim)bird1).swim();
  }
  
  Bird bird2 = new Pigeon();
  bird2.walk();
  if(bird2 instanceof Fly){
   ((Fly)bird2).fly();
  }
  if(bird2 instanceof Swim){
   ((Swim)bird2).swim();
  }
 }
}

Interface typecast helps to achieve this kind of behaviour.


Question 2.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

class SampleClass1 {
    public void test(){}
}
class SampleClass2 {
    public void test(){}
}

class MainTest {

    public void main(String[] args) {
     SampleClass1 sc1 = new SampleClass1();
     SampleClass2 sc2 = (SampleClass2) sc1;
    }
}

It will give Compile Time Error: "Cannot cast from SampleClass1 to SampleClass2".
Casting is possible only if there is Parent-child relationship between classes.


Question 3.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

interface SInterface1 {}

class SampleClass1 {}

class MainTest1 {
 public static void main(String[] args) {
  SampleClass1 sc1 = new SampleClass1();  
  SInterface1 sc2 = (SInterface1) sc1;
 }
}

It will NOT give Compile Time Error but will give Runtime Exception: 
"java.lang.ClassCastException: SampleClass cannot be cast to SInterface1".

Question here is why it didn't gave Compile time error?
Compiler is really not sure here to give compile error because sc1 at runtime can be reference of 
class SampleClass2, say (class SampleClass2 extends SampleClass1 implements SInterface1) in that case typecasting is perfectly valid. So Compiler doesn't give Compile error in this case, but when you run the program it sees that sc1 doesn't point to class that implements SInterface1 and that is why it cannot be typecasted.

Valid typecase possible at runtime,
interface SInterface1 {}
class SampleClass1 {}

class SampleClass2 extends SampleClass1 implements SInterface1{}

class MainTest1 {
 public static void main(String[] args) {
  SampleClass1 sc1 = new SampleClass1(); 
  sc1 = new SampleClass2();
  SInterface1 sc2 = (SInterface1) sc1;
 }
}



Question 4.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

class ClassA{}
class ClassB{}

interface InterfaceI{}

class MainTest11 {
 public static void main(String[] args) {
  InterfaceI i = (InterfaceI)(new ClassA());
  ClassA b = (ClassB)(new ClassA()); 
 }
}

It will give Compile Time Error: "Cannot cast from ClassA to ClassB" at line 9.
It will give Runt Time ClassCastException: "ClassA cannot be cast to InterfaceI" at line 8.

Check below image for better understanding of how Compiler treats casting to 
Reference and Class,


Question 5.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

interface Interface1 { }
interface Interface2 { }
class Class1 implements Interface1 { }

class Test{
 public static void main(){
  Class1 c1 = new Class1();
  String str = new String("Hello"); //OR Integer str = new Integer(1); 

  Interface2 x = (Interface2)c1;  //why compiler does not complain here?
  Interface2 y = (Interface2)str; //why compiler complains here?
 }
}
It will not give Compile time Error at line 10 but gives Compile error at line 11, why?
According to Question 4, which explains rules of typecasting,

Interface2 x = (Interface2) c1;

Compiler will not care what c1 is, it just validates "whether c1 can be object of a Class which is subclass of c1's class type and implements Interface2"? 

For line 10, that is possible because there can be class like,
Class A extends Class1 implements Interface2{}
c1 = new A();
Interface2 x = (Interface2)c1;

For line 9, that is not possible, str can't be object of class,
  1. which extends String class and (This is not possible)
  2. Implements Interface2. (This is possible)
String is as final class, So no class can be subclass of (extends) String class, that is why compiler is sure and gave compile error at line 11.

If we declare Class1 final, then compiler will complain at line 10 as well.

More Questions on Type Casting here

Top 10 Exception Handling Interview Questions Answers.


What is Exception handling?

Any program is a set of instructions executing in predefined sequence, but due to some Run-time Error or Exceptions program flow gets disturbed and gives erroneous result and to handle this un-expected behavior or condition is known as Exception handling. 

There are mainly 2 types of problems that can occur at run time,
1. Error: It is further classified into,
  1. Compile time error.
    (Error that are known and catch at Compile time are Compile time error, It occurs mainly due to Syntax error)
  2. Runtime error
    (Error that are unknown at compile time but occur at run time are Run time error.
    Example: Recursive call to method may lead to Stack overflow error)
2. Exception: It is further classified into,
  1. Checked Exception
    (Exception that are checked at compile time is known as Checked exception)
  2. Unchecked Exception
    (Exception that are not checked at compile time is known as Unchecked exception)

Let's see which all exception and checked and unchecked



Interview Questions on Exception Handling in Java?


Question 1. What is the output of below program? 
class ExceptionExample {

 public static void main(String[] args) {
  System.out.println("Value of a :"+test());
 }
 
 private static int test(){
  int a = 10;
  try {
   return a;
  } catch (Exception e) {
   a = 20;
   System.out.println("a in catch : "+a);
  }finally{
   a = 30;
   System.out.println("a in finally : "+a);
  }
  a = 40;
  System.out.println("a outside try-catch : "+a);
  return a;
 }
}

Output:  
a in finally : 30
Value of a :10
 

Why value of a is printed as 10 in main() method?

The order of return statements matters a lot. 
First return statement is encountered in try block, So at this point JVM will take a note of value of "a" and whatever is the value of "a" at this time will be the marked as the return value of method. (JVM marks the value of "a" as value to return and not variable "a" as to return )

At that point value of "a" was 10, so JVM will mark 10 as return value, once the value to return is marked after this JVM has no relation with the variable "a".

After this point whatever is the value of "a" changed in either catch block or finally block will change the value of "a" but not the return value. 


Question 2. What is the output of below program? 
class ExceptionExample {

 public static void main(String[] args) {
  System.out.println("Value of a :"+test());
 }
 
 private static int test(){
  int a = 10;
  try {
   return a;
  } catch (Exception e) {
   a = 20;
   System.out.println("a in catch : "+a);
   return a;
  }finally{
   a = 30;
   System.out.println("a in finally : "+a);
   return a;
  }
 }
}

Output:  
a in finally : 30
Value of a :30
 

Why value of a is printed as 30 in main() method?

Note: return statements have overwriting behavior.
Finally block is guaranteed to be executed (except abrupt shutdown or calling System.exit()).

The return statement in the try block will be overwritten by the return statement in finally block. 

First return statement is encountered in try block, So at this point JVM will take a note of value of "a" and whatever is the value of "a" at this time will be the marked as the return value of method.
At that point value of "a" was 10, so JVM will mark 10 as return value

After this finally block gets executed and it overwrites the return statement of try block, 
So return value 10 is overwritten to new value of "a" that is value 30.


Question 3. Is it valid to write try block without catch block?
class ExceptionExample {

 public static void main(String[] args) {
  System.out.println("Value of a :"+test());
 }
 
 private static int test(){
  int a = 10;
  try {
   return a;
  }finally{
   return a;
  }
 }
}

Output: 
Value of a :10
 

Yes. It is perfectly valid to write try block without catch block.
Rule:
1. After try block, there can be direct finally block. OR
2. After try block, there can be direct catch block.

Note: Only try block without catch or finally is compile time error.


Question 4. Is below code valid?
class ExceptionExample {
 private static void test(){
  try { } catch (IOException e) {}     
 }
}

Output:  Compile time error: Unreachable catch block for IOException.
                This exception is never thrown from the try statement body


It is not allowed to catch a Checked Exception which is not thrown from try block except for class Exception and Throwable which has RuntimeException as subclass for which decision is taken at run time and not compile time.

Example:
class ExceptionExample {
 private static void test(){
  try { } catch (Exception e) {}     
 }
}
Above code is perfectly valid because catch block catches Exception class and even though it is checked exception, Compiler doesn't complain because compiler is not sure that catch block is wrote to handle checked exception or unchecked(Runtime) exception as Exception class can handle both so above code is perfectly valid.

Example:
class ExceptionExample {
 private static void test(){
  try { } catch (NullPointerException e) {}     
 }
}
Above code is perfectly valid and compiler doesn't complains because when you catch Unchecked exception that is either RuntimeException or Error or any subclass of it then compiler doesn't check what is written in try block because this Exception/Error can occur at run time, so for compilation it is perfectly valid call.


Question 5. Which exception will be thrown by code below?
class ExceptionExample {
 public static void main(String[] args) {
  test();
 }
 private static void test(){
  try{
   System.out.println("In try");
   throw new ArithmeticException();
  } catch(Exception e){
   System.out.println("In catch");
   throw new ArrayIndexOutOfBoundsException();
  } finally{
   System.out.println("In finally");
   throw new NullPointerException();
  }
 }
}


Output:  NullPointerException will be thrown in output.               
                Initially ArithmeticException will be thrown which is catch by catch block, 
                catch block throws ArrayIndexOutOfBoundsException which is Runtime Exception and 
                actually no need to catch it(same is for ArithmeticException but handler was there so it 
                catch it.) after that finally block is executed and it throws NullPointerException. 
                So the final exception thrown by test() method is NullPointerException.


Question 6. Which will be output of code below?
class ExceptionExample {
 public static void main(String[] args) {
  test();
 }
 private static void test(){
  throw new Exception();
 }
}


Output:  Compile Time Error : Unhandled exception type Exception
                Exception class is checked exception and when some method throw CHECKED exception,
                then it requires a handler for checked exception or the method itself throws the exception 
                claiming as I am not going to handle exception and whoever calls me need to be handled. 

                So test() method here doesn't provided a handler for it nor it throws Exception as  
                indication to compiler that it is not going to handle it that is why it is compile time error.


Question 7. Which will be output of code below?
class ExceptionExample {
 public static void main(String[] args) {
  test();
 }
 private static void test() throws NullPointerException{
  throw new NullPointerException();
 }
}

Output:  Program will compile properly and it will throw NullPointerException at Runtime.
                test() method throws NullPointerException which is Unchecked exception, 
                So it is not mandatory for caller to catch it, If it catches still it is fine, that is why compiler 
                doesn't complain for catch block.


Question 8. Which will be output of code below? Do you think compiler will complain as "The type ExceptionExample must implement the inherited abstract method InterfaceTest.test()"?
interface InterfaceTest{ 
 public void test() throws Exception; 
}

class ExceptionExample implements InterfaceTest{ 
 public void test() throws Exception, IOException, RuntimeException, Error {
 }
 
 public static void main(String[] args) {
 }
}

Output:  Program will compile properly and no output.
                In InterfaceTest, one method is declared name test() which throws Exception. 
                So for the class which implements InterfaceTest need to define method test() which either 
                throws Exception class or any number of subclass of Exception and is perfectly valid 
                inherited test() method.


Question 9. What is the output of Program below?
class ExceptionExample{ 

 public static final void main(String[] args) {
  System.out.println(test());
 }

 private static String test() {
  try {
   String str = null;
   return str.toString();
  
  }finally {
   return "hello finally";
  }
 } 
}

Output:  hello finally (and no exception is thrown)
                How come NullPointerException is not thrown? So as we see in previous example, 
                finally block if present will always be a deciding block for return value of method if return
                statement is present in finally block irrespective of return present in try and catch block.

                In try block NullPointerException is thrown but and as it is Unchecked exception compiler 
                didn't complain for handling it and it is generated at run time. 

                After executing try block NullPointerException is generated but that is not the output of 
                the program as finally block was present in method which is returning "hello finally", 
                So control went to finally block and it encountered return statement there, which is final 
                return of method and exception which JVM planned to return after final block execution
                get lost.


Question 10. What is the output of Program below?
class ExceptionExample{ 

 public static final void main(String[] args) {
  System.out.println(test());
 }

 private static boolean test() {
  boolean flag = false;
  
  try{
   return true;
  }
  catch(Exception e){}
  finally{}
  
  System.out.println("Outside try-catch-finally");
  return flag;
 } 
}


Output:  true
                Why control never reached to line "Outside try-catch-finally" because in try block JVM 
                encountered return statement, which is indication for JVM to return from here, but as a 
                contract to execute finally block always (except in few conditions), finally block get 
                executed which doesn't contain any statement, so control returned from finally back to try 
                block and method returned from there without executing statements after finally block.


More Questions on Exception Handling here

When to use Interface and Abstract class in Java?


When to use interface and abstract class in java with real time example. interface vs abstract class in oops. difference between interface and abstract class.

This is very popular interview question for the beginners as well for experienced. 


interface Vs abstract class in Java.


Interface: 
Interface is used when you want to define a contract and you don't know anything about implementation. (here it is total abstraction as you don't know anything.)
Abstract class:
Abstract class is used when you know something and rely on others for what you don't know.(here it is partial abstraction as some of the things you know and some you don't know.)
Now, Let's understand above difference between Interface and Abstract class with real world project example.

When to use Interface
Scenario, 
Consider we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "airasia", "british airways" and "emirates".
  2. Place and order for seat to respective vendor.

How should we design our application considering interfaces and abstract class? In this scenario, interface is useful or abstract class?

Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "airasia", then enquire "british airways" and at last enquire "emirates" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "airasia", "british airways" and "emirates" to give us list of flights, internally how they are giving the list that we don't care.
  1. This means I only care for method name "getAllAvailableFlights()"

    "getAllAvailableFlights()" from
    "airasia" may have used SOAP service to return list of flights.
    "getAllAvailableFlights()" from "british airways" may have used REST service to return list of flights.
    "getAllAvailableFlights()" from
    "emirates"
    may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "
    getAllAvailableFlights" that all the flight vendor should provide and return list of flights.

  2. Similarly, for booking I only care for method name "booking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract.
So we can say that we know the contract that irrespective of who the Flight vendor is, you need "getAllAvailableFlights()" and "booking()" method from them to run our aggregator service.
In this situation, Interface is useful because we are not aware of the implementation of all the 2 methods required, and what we know is the contract methods that vendor(implementer) should provide. so due to this total abstraction and for defining the contract, interface is useful in this place.
Technically, we need to design our interface somewhat like below,

FlightOpeartions.java(Contract)
interface FlightOpeartions{
 void getAllAvailableFlights();
 void booking(BookingObject bookingObj);
}
BookingObject.java
class BookingObject{}
BritishAirways.java (Vendor 1)
class BritishAirways implements FlightOpeartions{

 public void getAllAvailableFlights(){
           //get british airways flights in the way 
           //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
          //place booking order in a way British airways 
          //told us to place order for seat.
 }

}
Emirates.java (Vendor 2)
class Emirates implements FlightOpeartions{

 public void getAllAvailableFlights(){
         //get Emirates flights in the way 
         //they told us to fetch flight details.
 }

 public void booking(BookingObject flightDetails){  
         //place booking order in a way Emirates airways
         //told us to place order for seat.
 }
}


Please see detailed post here

You may also like to see


Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

How Thread.join() in Java works internally

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

Type Casting Interview Questions In Java

How is ambiguous overloaded method call resolved in java

Method Overriding rules in Java

Interface interview questions and answers in Java

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Post a Comment