51 frequently asked java interview questions and answers for freshers (0-2 Years Experience) - Part 3(Q#21 to Q#30)

In previous posts we have explained Q#1-Q#10 and Q#10-Q#20 and here follows from question 21.
21.What do you mean by nested class/inner class in Java? What are different kind of inner classes in Java ?
Answer: In Java a class created inside a class or interface are termed as nested classes. Nested classes are broadly divided in two category:
  1. Static nested class : class qualified with static modifier 
  2. Non-static nested class: these classes are called inner classesInner class can be further divided into following category:
    • Member inner class - class defined inside a class but not inside blocks (method, for loop, if clause)
    • Local inner class - class declared inside a method or blocks(for loop, if block, etc).They cannot define or declare any static members(except static members are constant variables.).We cannot declare an interface inside a block,interfaces are inherently static.
    • Anonymous inner class- declare and instantiate a class at the same time, it is one of local class without a name.

22. What is thread ? Can you explain thread life cycle? Does Java support threading, if yes, then how?
Answer: A thread is single(smallest) sequence of programmed instruction executed inside a process. The processes(heavyweight) have a single thread of control, however in multi-threaded
environment, a single process(collection of instructions) is executed by multiple thread in parallel and managed by CPU(Operating system).Java expose threading API to the developer while abstracting the platform specific differences in threading implementations. It is JVM that translates API call to OS calls and makes thread handling easy for developer.
Thread life cycle :-  Newly created thread is submitted with CPU for scheduling(allocating time slice) and it goes into to runnable state. When CPU allocates time slice to this thread, its state changes to running and thread executes its program unit(instruction sets) here. If thread does perform I/O operation then it goes into blocked state and threads are idle and again it return back to runnable state.Once thread complete its task and it gets terminated and thread is dead.Following diagram summarize thread life cycle and its state transition.

23. What are different ways you can create thread in Java? Pros/cons of one over another ?
Answer: By extending "java.lang.Thread" class and by implementing "java.lang.Runnable" interface we can create threads in Java. Implementing Runnable interface is most commonly used to create thread.Lets understand important differences between them and consider following point while choosing which one to use:
  1. When a class extends Thread class, that class misses an opportunity to extend another class because Java does not support multiple inheritance, however when we implements Runnable interface we still have option do extend another class. 
  2. When a class implements Runnable interface, still that class is just a normal class with Run method. We need a runner either in form of Thread class(or Executors) to make Runnable to behave like a thread. It might difficult to understand, we will revisit it while writing sample code lines. In other words, Runnable object requires a carrier to carry out execution of their ask.
    By implementing Runnable we are architecturally separating the "task" (Runnable) from the "runner"(Thread class).
  3. If we implement Runnable interface, task is loosely coupled with runner and if at some point we feels that it does not require separate thread to execute, then call run() method directly as normal method. 
  4. Another important point , why we should carry overhead of inheriting all Thread class method, just implement run() of Runnable and Thread class will run our task. Inherit less, interface more. 
Lets write sample program creating Thread using both Runnable interface and Thread class to understand differences from syntax perspective.
Thread creation by implementing Runnable interface :-
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadInJavaExample {
  public static void main(String[] argsthrows InterruptedException {
    ImplementsRunnable rc = new ImplementsRunnable();//rc is Runnable object
    // Case 1: Thread class is runner for rc.
    Thread t1 = new Thread(rc);
Case 2: Executors used as the runner for rc. 
    ExecutorService es = Executors.newCachedThreadPool();
Case 3: Execution as instance method, executed in main thread context


class ImplementsRunnable implements Runnable {
  private int count = 0;
  public void run() {
    System.out.println("ImplementsRunnable Count " + count);
In the above program, ImplementsRunnable class implements Runnable interface and implement run() method. In main method, we create an object of ImplementsRunnable and it is passed to a runner Thread t1 (Case 1).With t1.start() , it executes run() method of the ImplementsRunnable. Similarly, we have used ExecutorService as runner to execute run method of  ImplementsRunnable (It is recommended to use ExecutorService to launch thread if you are using java 5 and later).It validates point no 2 mentioned above.At the end, we have directly called run() without any runner, as an instance method.It explains point 3 mentioned above. For simplicity just understand, how do we use Thread class to execute run method of Runnable object, ignore executors concept as of now.

Thread creation by extending Thread class:-
public class ThreadInJavaExample {
  public static void main(String[] argsthrows InterruptedException {
    ExtendsThread et = new ExtendsThread()//By default,it becomes a new thread.


class ExtendsThread extends Thread {
  private int count = 0;
  public void run() {
    System.out.println("ExtendsThread Count" + count);
Here, we do not need to create Thread class object explicitly as contrast to Runnable interface. By default, classes extending Thread class, its object become a Thread and we can directly call start() method. A detailed discussion of Thread VS Runnable can be found here.

24.What happens when we call run() method directly instead of calling start() method on a thread ?
Answer:  Instead of calling start() method by an thread if we directly call run method then run() will be executed in the context of the current thread from where it was called.Consider the following sample program and its output.
public class DirectRunMethodCall {
  public static void main(String[] argsthrows InterruptedException {
    ThreadContext tc = new ThreadContext();
    Thread t1 = new Thread(tc, "Thread-1");// Thread name is Thread-1
    // call run() method directly instead of start() call.
    t1.start();// call from "Thread-1" context

class ThreadContext implements Runnable {
  public void run() {
    Thread thread = Thread.currentThread();
    System.out.println("Call from context of thread name: "
        + thread.getName());
Sample output:
Call from context of thread name: main
Call from context of thread name: Thread-1
In above sample program, even tough run method is called using thread object t1 (t1.run()), run() of Runnable object is executed in context of main thread. And when same object makes a call to start() method, then run() of Runnable is executed in the context of Thread-1.

25. What do you understand from synchronization method or block in Java ?
Answer: In multi-threaded environment,consider threads shares some resource and each thread is equally qualified to perform write operation or modify it, then a race condition arises (which thread will run when) and it may lead to problem of thread collision and inconsistency.Concurrent execution of threads requires some way to prevent two threads from accessing the same resource, at least during critical periods(block of codes where shared resources are modified are called critical block). In order to prevent collision over resources, put a lock(also called mutex) on resource and only one thread is allowed to use resource and other thread will wait until working thread releases the lock.
Java has built-in support in the form of the synchronized keyword to deal with resource collision situation. synchronized keyword can be used with a block(critical section code) and method in Java. All objects in Java automatically contain a single lock (also referred as a monitor), which any thread can lock or unlock. All synchronized methods shares a single lock for a particular object, and this lock can be used to prevent object memory from being written by more than one thread at a time.
  • One thread may acquire an object’s lock multiple times. This situation arises when one method calls a second method on the same object, which in turn calls another method on the same object. The JVM keeps track of the, number of times lock acquired on an object and it increments/decrements count accordingly.
  • Along with single lock per object we have single lock per class also ,which is relevant for static synchronized method. 
//Synchronized method definition: 
  public synchronized void methodName() { 
    //shared resources modification and uses... 
//Synchronized block definition: 
  public void methodName(){
    synchronized(PD) { 
      //critical operation 
Note : Always prefer to use synchronized block over synchronized method.

26.What is Inheritance in Java? Explain with an example. Does Java support multiple inheritance ?
Answer: Suppose class A(derived class) extends class B(base class), then class A inherit class B properties (public and protected fields and methods), it is termed as class A and B form inheritance tree or exhibit inheritance relationship.
Java does not support multiple inheritance, i.e : More than one class cannot be extended by particular class. Please refer Question 8 for detailed example of inheritance.
Note: Multi-level inheritance(class A extends B, class C extends A) is different from multiple inheritance.

27. Where do we use "protected" access modifier in Java? What are different access modifiers being used in Java ?
Answer: "protected" is one of the member(fields and methods) level access modifier used in Java. It allows member to accessible from from "same package" and a subclass existing in any package can access.
There are four access modifiers used in Java: public, private, protected, no modifier (also termed as package-private, default).
  • Class level access modifiers: Only two modifiers "public" and "no modifier" are allowed for Java classes.
    Public : Accessible from anywhere.
    Default/No modifier:  Only accessible in given package(package-private visibility scope) 
  • Member (fields and methods) level access modifier: There are four valid access modifiers for class members: private, protected , public, default/no-modifier.Following table gives holistic view of member level access modifier. 
Access Modifiers Same Class Same Package Subclass Other packages
protected YES YES YES NO
no access modifier YES YES NO NO
private YES NO NO NO

28. What do you mean by dynamic binding in Java? Explain with an example.
Answer: Please refer to Question # 8 answer for detailed explanation.

29. What is static binding in Java ?/ What is compile time binding ?
Answer: Please refer to  Question # 8 answer for detailed explanation.

30.What is basic criteria of distinguishing overloaded methods ?
Answer: A group of method in a class is said to be overloaded, if they satisfies following conditions:
  1. Method name should be same for all methods.
  2. Data type of method parameters should be different or varies with other methods. (OR)
  3. Number of method parameters are different. (OR)
  4. Combination of both 3 and 4. 
Note: Return type of methods does not participate in determining overloading criteria.

Previous: Part 2(Q#11 to Q#20 ) - Interview Q&A Next: Part 4(Q#31 to Q#40 ) - Interview Q&A


Previous Post Next Post