34 Java Interview Questions for Intermediate in 2021: Part 2

34 Java Interview Questions for Intermediate in 2021: Part 2
34 Java Interview Questions for Intermediate in 2021: Part 2

Introduction

The Java programming language created by James Gosling in the early 1990s is one of the most popular programming languages. No wonder Java is the second most demanded programming language with around 70K job postings in January 2020, as per Indeed. Over 90% of the Fortune 500 companies still rely on Java for their development projects, and globally there are over 8 million Java developers.

So if you get an interview call for the Java developer role and are looking for a quick guide before your interview, then you have come to the right place. The whole blog consists of 100 interview questions divided into three parts: Beginner, Intermediate and Advanced. This article is Part 2 of the Java Interview Questions and Answer Series covering intermediate-level questions.

Intermediate Java Interview Questions

Question 1) What do you know about the JIT compiler?

Answer 1) The JIT or Just in Time compiler does the task of compiling parts of byte code having similar functionality simultaneously, thereby reducing the amount of compilation time for the code to run.

Working of JIT compiler in Java programs:

  1. The .java source code file is converted into a .javac file using the javac compiler.
  2. The .class files are loaded at run time by JVM. With the help of an interpreter, the .class files are converted into machine-understandable code.
  3. JIT compiler is a part of JVM. The JIT compiler analyzes the method calls in the .class files and compiles them to get more efficient and native code.
  4. Now the optimized code is executed directly by the JVM instead of interpreting the code again. This increases the speed of execution.

Question 2) Can a single try block with multiple catch blocks exist?

Answer 2) A try block can be followed by one or more catch blocks. Each catch block contains a different exception handler. In the case of multiple catch statements, priority would be given based on the order in which they are defined, i.e., the highest priority would be given to the first catch block. If the first catch block cannot handle the exception, then the second catch block will be considered.

Consider the following example with a single try block and multiple catch blocks.

public class Demo {
    public static void main(String args[]) {
    // A single try block with three catch blocks
      try{
          int[] arr = new int[6];
          arr[7] = 10;
          System.out.println("try block executed successfully");
      }
      catch(ArithmeticException e){
          System.out.println("Arithmetic Exception occurred");
      }
      
      catch(ArrayIndexOutOfBoundsException e){
          System.out.println("Array Index out of bound exception occured");
      }
      catch(Exception e){
          System.out.println("Some other exception");
      }
      
      System.out.println("Rest of the code");
    }
}

The output of the code will be:

Array Index out of bound exception occurred
Rest of the code

Question 3) Immutable nature of string in Java is advantageous for many reasons. Why?

blog banner 1

Answer 3) The immutable nature of strings provides the following advantages:

  1. String Literals can be stored in String Pool: A string pool is a storage area inside the heap memory for storing string literals. String literals are shared; suppose there are ten string literals each storing, “Java” now these ten literals will point to a single memory location inside the String Pool which stores “Java”. To facilitate such sharing of objects, string literals must be immutable. String pool exists only because Strings are immutable.
  1. The immutable nature of strings makes it thread-safe: In the case of a multithreaded program wherein a string is modified by a single thread, then the original string won’t be modified, else a new String will be created in the String Pool.
  1. Collections:  The key value in the case of HashMaps and Hash Tables are String objects. If the string objects were mutable, then the key-value may get modified during the period it resides in the HashMap. Consequently, the retrieval of desired data is not possible. This will pose a lot of problems. Therefore it’s quite safe to make strings immutable.

Question 4) If you want to store confidential information, which one will you choose, character array or strings?

Answer 4) A string once declared stays in the String Pool as long as it is not removed in the form of garbage. Anyone who has access to the memory dump can access confidential information.

However, in the case of character arrays, they can be set back to blank after the work is done. So for storing confidential information, a character array is preferred over strings as it mitigates the risk of theft.

Also, using strings, there are chances that the confidential information is accidentally printed straightaway to logs, monitors, or some other insecure places. While when using character arrays, confidentiality is maintained as the data cannot be printed straightaway.

Consider the below example for better understanding.

public class Demo {
    public static void main(String args[]) {
        String password = "ABCDEF";
        char[] pswd = new char[]{'A','B','C','D','E','F'};
        
        // This will print the password straightaway
        System.out.println("Password stored in String: " + password);
        // This will print the memory location of the character array
        System.out.println("Password stored in character array: " + pswd);
    }
}

The output of the above program will be:

Note that even Java recommends using the getPassword() method of JPasswordField, which returns a char[] array.

Question 5) What is the difference between Thread and Process?

Answer 5) 

ProcessThread
A process is any program under execution that runs in separate memory spaces.A thread is a subset of a process that runs in shared memory spaces
Processes must communicate via inter-process communicationThreads can directly communicate with other threads of the process.
Any change in the parent process does not affect child processes.Change in the main thread may affect the behavior of the other threads of the process.
A process has its own Process Control Block, Stack, and Address SpaceA thread uses its Parent’s Process Control Block. A thread has its Thread Control Block, Stack, and common address space.
A process is an independent entity.Threads are dependent entities.

Question 6) Explain the lifecycle of the thread?

Answer 6) The life cycle of the thread is as follows:

  1. New: When an instance of a thread is created but the start() method is not yet invoked, the thread is considered to be in the New state.
  1. Runnable: After the invocation of the start() method and before the invocation of the run() method, the thread is said to be in the Runnable state.
  1. Running: When the thread has started its execution, i.e., when the run() method is invoked, the thread is said to be Running.
  1. Non-Runnable: When an alive thread is unable to run, maybe another thread is currently operating in that synchronized block on the same object(Blocked State) or it is waiting for the signal to execute from another thread(Waiting State).
  1. Terminated: Once the run() method has completed its execution, the thread enters the Terminated state and is considered as dead thread.

Question 7) What is Multithreading in Java?

Answer 7) In simple terms, Multithreading is the process of executing multiple threads simultaneously by sharing the process resources. The main purpose is to utilize the CPU time as much as possible. The following are the main advantages of Multithreading in Java:

  • It allows you to write effective programs that utilize maximum CPU time 
  • Many operations can be performed together, so it saves time and is less resource-consuming.

Question 8) What are the two ways to implement Thread in Java?

Answer 8)  There are two ways to implement Thread in Java.

  1. Extending Thread Class
// By extending Thread class
public class Demo extends Thread {
    public void run()
    {
        System.out.println("Thread is currently under execution");
    }
    public static void main(String args[]) {
      Demo d = new Demo();
      // start() method is used to start a newly created Thread
      d.start();
    }
}

The output of the above code is:

Thread is currently under execution
  1. Implementing the Runnable Interface
// By implementing runnable interface
public class Demo implements Runnable {
    public void run()
    {
        System.out.println("Thread running....");
    }
    public static void main(String args[]) {
      Demo d1 = new Demo();
     
      Thread t1 = new Thread(d1);
      t1.start();
    }
}

The output of the above code is:

Thread running….

Question 9) How do multiple threads communicate with each other?

Answer 9) Multiple threads can communicate with each other using three methods, i.e., wait(), notify() and notifyAll(). A thread that is in a waiting state will be in a waiting state until any other thread calls either notify() or notifyAll() method

  1. wait() : A non-static method that causes the current thread to wait and go to sleep until some other thread calls the notify() or notifyAll() method to release the lock.
  2. notify(): This method sends a notification and wakes up a single thread that was waiting for the object’s monitor.
  3. notifyAll(): This method sends a notification and wakes up all the threads waiting for the object’s monitor.

Question 10) Java works on a pass by value or pass by reference?

Answer 10) Java works on pass-by-value. When a primitive type is passed to a function, Java creates a copy of the variable being passed and then does the manipulations. So the changes made inside the method are not reflected inside the main method. Whenever an object is passed in any method, Java creates a copy of the reference and then passes it.

Question 11) A lot of updates need to be done in the data, which one is a preferred option, String or StringBuffer?

Answer 11) Strings are immutable. For every update, a new String object is created in the String Pool. Whereas String Buffers are mutable, the original object will be modified for every update instead of creating a new object. Hence, in the case of many updates, it is always preferred to use StringBuffer as it will reduce the overhead of creating multiple string objects in the String Pool.

Question 12) What is abstraction? How is abstraction achieved in Java?

Answer 12) Data abstraction deals with hiding the implementation details and showing only the functionality to the user. In simple words, the user will have information about what an object does instead of how it does it. An example could be sharing a post on social media, complex details such as protocol, database, etc are hidden from the user. All the user needs to do is upload and post.

Abstraction can be achieved in two ways:

  1. Abstract Classes: Using this 0-100% of abstraction can be achieved
  2. Interfaces: Using this 100% abstraction can be achieved

Question 13) Explain the difference between Abstract Classes and Interfaces?

Answer 13)

Abstract ClassesInterfaces
An abstract class can have both abstract and non-abstract methods.An interface can only have abstract methods.
An abstract class can only have non-static and non-final variablesAn interface can only have static and final variables.
They do not promote multiple inheritancesInterfaces facilitate multiple inheritances
The class members can be private, protected, etc.The class data members of interfaces are of the public type.

Question 14) Does Java support multiple inheritances?

Answer 14) Java does not support multiple inheritances. The problem arises when multiple parent classes have the same method name, then at runtime, it becomes difficult for the compiler to decide which one to execute. This problem is also referred to as the Diamond Problem.

 Question 15) What is Object Cloning?

Answer 15) The process of creating an exact copy of an object is called object cloning. In order to clone an object, a java class has to implement the Cloneable interface provided by the java.lang package and override the clone() method of Object class. The clone() method creates a new instance of the current object’s class and then initializes all the fields with the exact same content of corresponding fields.

Consider the below program that clones an object of Demo class.

// Demo class is implementing the Cloneable interface
public class Demo implements Cloneable{
  int rollno;
  int marks;
  String name;
  
 // Constructor of the demo class
  Demo(int rollno, int marks, String name)
  {
      this.rollno = rollno;
      this.marks = marks;
      this.name = name;
  }
  
  // Defining the clone method
 @Override
  public Object clone() throws CloneNotSupportedException
  {
      return super.clone();
  }
  
  public static void main(String[]args)
  {
      try
      {
          Demo s1 = new Demo(12, 20, "ABC");
          Demo s2 = (Demo)s1.clone();
          
          System.out.println(s1.rollno + " " + s1.marks + " " + s1.name);
          System.out.println(s2.rollno + " " + s2.marks + " " + s2.name);
      }
      
      catch(CloneNotSupportedException c)
      {
          
      }
  }
}

The output of the above program is:

12 20 ABC
12 20 ABC

Question 16) What are Copy Constructors?

Answer 16) A copy constructor is a constructor that creates an object by initializing it with the object of the same class created previously. Java does not provide an explicit copy constructor, and you need to define one.

Consider the following example to understand the Copy constructor

public class Demo implements Cloneable{
  private int rollno;
  private int marks;

  // Parameterized constructor to initialize the value of instance variables
  public Demo(int rollno, int marks)
  {
      this.rollno = rollno;
      this.marks = marks;
  }
  
  // Copy Constructor
  public Demo(Demo d)
  {
      this.rollno = d.rollno;
      this.marks = d.marks;
  }
  
  public void display()
  {
      System.out.println("Roll No: " + this.rollno);
      System.out.println("Marks: " + this.marks);
  }
  
  
  public static void main(String[]args)
  {
      Demo d1 = new Demo(12, 20);
      System.out.println("Showing the contents of the original object");
      d1.display();
      Demo d2 = new Demo(d1);
      System.out.println("Showing the contents of the copied object");
      d2.display();
  }
}

The output of the above program is:

Showing the contents of the original object
Roll No: 12
Marks: 20
Showing the contents of the copied object
Roll No: 12
Marks: 20

Question 17) Is it mandatory for a catch block to be followed after a try block?

Answer 17) It is not mandatory for a catch block to be followed after a try block unless and until the try block is followed by a finally block. A try block can be followed either by a catch block or by a finally block.

For more information refer to the blog.

Question 18) What is the collection framework in Java?

Answer 18)  A collection framework is a combination of classes and interfaces used for storing and manipulating data in the form of objects.

The collection framework consist of three categories:

  1. Collection Interfaces
  2. Collection classes that implement the interfaces.
  3. Collection Algorithms
collection_framework

Question 19) How to write a custom exception in Java?

Answer 19) Java allows the creation of user-defined exceptions, which are basically derived classes of Exception. Custom exceptions are mainly used to provide specific treatment to a subset of existing Java exceptions.

The below program illustrates using and defining Custom exceptions in Java

// class representing custom exception
class ExceptionDemo extends Exception 
{
    public ExceptionDemo(String str)
    {
        super(str);
    }
}

// class using the custom exception defined above
public class ExceptionTestingDemo
{
    static void validate(int age) throws ExceptionDemo
    {
        if(age < 45)
        {
            throw new ExceptionDemo("You have to register to get vaccinated");
        }
        else{
            System.out.println("You may get vaccine without registration too");
        }
    }
    
    public static void main(String[]args)
    {
        try{
            validate(5);
        }
        catch(ExceptionDemo ex)
        {
            System.out.println("Exception Caught");
            // Printing the message from the custom exception defined above
            System.out.println(ex);
        }
    }
}

The output of the above code will be:

Exception Caught
ExceptionDemo: You have to register to get vaccinated

Question 20) Explain the propagation of exceptions in Java.

Answer 20)  Whenever an exception occurs, first the matching catch block is being located. If the catch block is found, then the catch block is executed.

If the catch block is not found, the exception propagates through the method class stack, and the control is passed to the caller method where again the process of matching the catch block is performed. The propagation happens until the matching catch block is found.

To know more about Exceptions in Java, you may refer to this and this.

Question 21) What is the OutOfMemoryError in Java?

Answer 21) The java.lang.OutOfMemoryError happens when there is insufficient space to allocate an object in the Java Heap memory. The garbage collector cannot make sufficient space to accommodate a new object. The various cases in which the exception is raised is:

  • Error 1: Java Heap Space
  • Error 2: Garbage collection Overhead limit exceeded
  • Error 3: Requested Array Size exceeds VM limit
  • Error 4: Metaspace
  • Error 5: Request Size bytes for reason. Out of swap space?
  • Error 6: Compressed Class space
  • Error 7: stack_trace_with_native_method

You may refer to the official documentation to know more about OutOfMemoryError

Question 22) What are the rules that need to be followed when overriding a method that throws an exception in Java?

Answer 22) This question is frequently asked, sometimes an interviewer may ask specifically for a particular case as well.

The following set of rules need to be followed when overriding a method that throws an exception in Java:

If the Superclass method does not declare an exception, then 

  1. Subclass overridden method cannot declare the checked exceptions

          The following program will generate an error:-

import java.io.*;
public class ParentClass 
{
    // Parent Class does not declare an exception
    void display()
    {
        System.out.println("Parent Class Method");
    }
}  // ParentClass ends here

public class ChildClass extends ParentClass
{
    // subclass overridden method declare
    // checked exception
    void display() throws IOException
    {
        System.out.println("Child Class Method");
    }
    
    public static void main(String[]args)
    {
        ParentClass obj = new ChildClass();
        obj.display();
    }
}
  1. Subclass overridden method can declare an unchecked exception

The following program will work fine

 import java.io.*;    
class Parent{  
  // Parent class method does not declare any exception  
  void display() {  
    System.out.println("Parent Class Method");  
  }    
}    
    
public class Child extends Parent{    
  // Child class method declare unchecked exception
  void display()throws ArithmeticException {    
    System.out.println("Child Class Method");    
  }    
  
  public static void main(String args[]) {    
   Parent p = new Child();    
   p.display();    
  }    
}  

The output of the above program will be:

Child Class Method

If the superclass method declares an Exception

  1. Subclass overridden method cannot declare Parent exception
import java.io.*;
class ParentClass
{
    // Parent Class declaring an exception
    void display() throws ArithmeticException
    {
        System.out.println("Parent Class Method");
    }
}

public class ChildClass extends ParentClass
{
    // Subclass overridden method is declaring parent exception
    void display() throws Exception{
        System.out.println("Child Class Exception");
    }
    
    public static void main(String[]args)
    {
        ParentClass obj = new ChildClass();
        try{
            obj.display();
        }
        
        catch(Exception e){
            
        }
    }
}

The above code when compiled will give the following error message

  1. Subclass overridden method can declare the same Exception
import java.io.*;
class ParentClass
{
    // Parent Class declaring an exception
    void display() throws Exception
    {
        System.out.println("Parent Class Method");
    }
}

public class ChildClass extends ParentClass
{
    // Subclass overridden method is declaring same exception
    void display() throws Exception{
        System.out.println("Child Class Method");
    }
    
    public static void main(String[]args)
    {
        ParentClass obj = new ChildClass();
        try{
            obj.display();
        }
        
        catch(Exception e){
            
        }
    }
}

The output of the above program will be:

Child Class Method
  1. The overridden method can declare subclass exceptions.
import java.io.*;
class ParentClass
{
    // Parent Class declaring an exception
    void display() throws Exception
    {
        System.out.println("Parent Class Method");
    }
}

public class ChildClass extends ParentClass
{
    // Sub class overridden method is declaring subclass exception
    void display() throws ArithmeticException{
        System.out.println("Child Class Method");
    }
    
    public static void main(String[]args)
    {
        ParentClass obj = new ChildClass();
        try{
            obj.display();
        }
        
        catch(Exception e){
            
        }
    }
}

The output of the above program will be:

 Child Class Method
  1. Subclass overridden method can declare no exception
import java.io.*;
class ParentClass
{
    // Parent Class declaring an exception
    void display() throws Exception
    {
        System.out.println("Parent Class Method");
    }
}

public class ChildClass extends ParentClass
{
    // Subclass overridden method is declaring no exception
    void display(){
        System.out.println("Child Class Method");
    }
    
    public static void main(String[]args)
    {
        ParentClass obj = new ChildClass();
        try{
            obj.display();
        }
        
        catch(Exception e){
            
        }
    }
}

The output of the above program is:

Child Class Method

Question 23) What is the difference between Checked and unchecked exceptions in Java?

Answer 23) The difference between Checked and unchecked exceptions is summarized in the following table

Checked ExceptionsUnchecked Exceptions
Checked exceptions occur at compile time Unchecked exceptions occur at run time
Exception class is the direct parent class of the checked exception subclass.RuntimeException is the direct parent class of the Unchecked exception subclass.
A checked exception occurs where the chances of failure are too high.Unchecked exceptions occur primarily due to syntax or semantic errors.

You may refer to our blog on Checked Exception and Unchecked Exception.

Question 24) How many objects will be created in the following code, and where will they be stored?

String s1 = new String("Java Interview Questions");
String s2 = "Java Interview Questions"

Answer 24) Two string objects will be created. String s1 will be stored in the heap memory while string s2 will be stored in the String constant pool.

Question 25) What will be the output of the following code.

public class Demo{
    public static void main(String[] args)
    {
        System.out.println('J' + 'a' + 'v' + 'a');
    } 
}

Answer 25) The output of the above code is 386. The reason is the print statement has character literals in single quotes, so instead of concatenation, the corresponding ASCII value of each character is added, and the result is displayed as 386.

Question 26) In the program given below, what is the significance of …?

public void demoMethod(String… variables)
{
          // Code here
}

Answer 26) The … is a feature called varargs or variable arguments. The function having … indicates that it can receive multiple arguments of the data type String.

Consider the following example to understand the concept of variable arguments.

public class Demo{
    // the display method can receive a variable number of arguments
    static void display(int ... a)
    {
    System.out.println("Number of arguments passed: " + a.length);
  
        // using for each loop to display contents of a
        for (int i: a)
            System.out.print(i + " ");
        System.out.println();
    }
    public static void main(String[] args)
    {
       // Passing variable number of arguments to the display method
       display(10);
       display(20, 30, 40);
       display(1, 2, 3, 4, 5, 6, 7, 8);
    }
   
}

The output of the above program is:

Question 27) In case a package has sub-packages, will it be sufficient to import only the main package?

Answer 27)  In case a package has sub-packages, it will not be sufficient to import only the main package. Importing of the sub-packages needs to be done explicitly. Importing the main package only imports the classes of the main package and not the sub-packages.

Question 28) What is the difference between Arrays and ArrayList in Java?

Answer 28)

ArraysArrayList
An array is a container that holds the constant number of values of the same type.It is a class of collection frameworks.
An array can store both objects and primitive typesArrayList cannot store primitive types.
A for loop or for each loop is used to iterate over an arrayAn iterator is used to iterate over ArrayList.
Arrays can be one-dimensional or multidimensional An ArrayList can only be one-dimensional.
It’s a fixed-size data structure. The size of the array need to be mentioned at the time of declaring an arraySize is not fixed. Even if an initial capacity is specified, we can always add more elements.

Question 29) What is the difference between String, StringBuffer, and StringBuilder in Java?

Answer 29) There are three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. 

StringStringBufferStringBuilder
String Pool serves as the storage area.Heap Memory serves as the storage area.Heap memory serves as the storage area.
Strings are ImmutableThey are mutableThey are mutable
Strings are generally not used in the case of a threaded environment.StringBuffer is suitable for multiple threadsStringBuilder is suitable for an environment with single threads
It is quite slow to work with a stringSpeed of a StringBuffer is more than String and less than StringBuilderStringBuilder is the fastest in performing operations.

Question 30) What do you mean by Association, Aggregation, and Composition?

Answer 30) In object-oriented programming, an object communicates with other objects to use the functionality and services provided by that object.

Association:  The relationship between multiple objects is called an Association. Association refers to how different objects are related to each other and how they are using each other’s functionality. An example could be the relationship between Teacher and Student. Multiple students can associate with a single teacher, or a single student can be associated with multiple teachers, but there is no ownership between the two objects, and each has its own lifecycle. Composition and Aggregation are two types of association.

Composition: An association is a composition if an object owns another object and the other object cannot exist without the owner object. An example could be the relationship between Heart and Human, wherein the Human is the parent object and the heart is the child object. The heart cannot exist without humans. It’s a strong type of Association.

Aggregation: An association is an aggregation where all objects have their own lifecycle, but there is ownership. All the objects can however exist independently. An example could be the relationship between Department and Teacher, a teacher belongs to one department, and if the department object is deleted,  the Teacher object can still exist independently.

Question 31) Inheritance is considered less advantageous than Composition. Explain.

Answer 31) Inheritance lags behind composition in the following scenarios:

  • Java does not support multiple inheritances. In cases where multiple functionalities are required, the pattern of composition is preferred. The multiple functionalities can be made use of by treating them as private members.
  • Unit Testing is possible with composition and not with inheritance.

Question 32) When is the runnable interface preferred over the thread class and vice versa?

Answer 32) Runnable interface is preferred over Thread class because of the following reasons:

  1. Other classes can be extended as well when using Runnable Interface. However, when using the Thread class, other classes cannot be extended as Java supports only Single Inheritance.
  2. Instantiating an interface gives a cleaner separation between the code and the implementation of threads

Answer 33) What is Garbage Collection?

Question 33) Garbage means unreferenced objects. Garbage collection is the process of reclaiming the runtime unused memory automatically to destroy the unused objects.

Java provides four types of garbage collectors:

  1. Serial Garbage Collector
  2. Parallel Garbage Collector
  3. CMS Garbage Collector
  4. G1 Garbage collector.

Question 34) When does an object become eligible for Garbage collection?

Answer 34) An object becomes eligible for garbage collection when:-

  • It is marked as Null
  • The object goes out of scope
  • The object is no longer referenced by any non-null objects within an application.

Key Takeaways

The article discussed frequently asked Java interview questions for professionals with an intermediate level of experience. Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and to get placed at your dream company. 

By: Manvi Chaddha