MNCs Choice Java Interview Question For Experienced

If Your are struggling to find the most important and frequently asked face two face c interview questions, Then hold down and take a deep breath because you are at the right place.

I know that It is very tough for fresher students to prepare for an interview as well as finding some great bunch of right questions that cover the most important topics.
In this section, I have tried to cover all important and most asked c programming interview questions topics wise.
Let us start Preparing.

Java interview questions for Experienced MNCs

Q1). Tell me something about HashMap in Java

Ans:

HashMap is a Collection class in Java whose implementation is based on the hash table data structure. HashMap class extends AbstractMap class and AbstractMap class implements the Map interface.

Some Important points about Hashmap:

  • HashMap allows only one null key and multiple null values.
  • HashMap does not maintain the order of insertion into the map.
  • The initial size of the hashmap bucket is 16 which grows to 32 when the map entries cross 75%.
  • HashMap uses hashCode() and equals() methods on keys to perform put and get operations. It internally checks whether the key already exists or not.
  • Hashmap is not a thread-safe. This is the reason it won’t use in a multithreaded environment. 

Q2). What are load Factor, Threshold, Rehashing, and collision in hashmap?

Ans:

Load factor is the measure to decide when to increase the size of the Map. By default, the load factor is 75% of the capacity.

The threshold can be calculated by multiplying the current capacity and load factor. 

Rehashing means, re-calculating the hash code of already stored entries. When entries in the hash table exceed the threshold, the Map is rehashed and increases the size of buckets.

Collision is a condition when a hash function returns the same bucket location for two different keys.

For example:

Suppose Our HashMap has an initial capacity is 16 and a load factor is 0.75. 

Threshold will be 16 * 0.75 = 12, 

It means after the 12th entry in the hashmap, the capacity of the hashmap will increase from 16 to 32.

Q3). How does HashMap Internally work in Java?

Ans:

A HashMap in Java is a data structure that stores date in key-value pairs. It is useful for the fast retrieval and insertion of values based on their keys. It internally uses an array of buckets to store these key-value entries. In hashmap one key can have only one hash output. Two key can also result same output but one key can’t result two output.

General steps for how a HashMap works internally?

Hashing: When you insert a key-value pair into a HashMap, the hash code of the key is computed using the hashCode() method of the key object. This hash code is used to determine the index or bucket in the array where the entry will be stored.

Eg:

for Large Key :– hashcode(key) = key%m

For String key :- Weighted sum

Suppose key is “cat” then hashcode() will be (s[0]*x^0 + s[1]*x^1 + s[2]*x^2)%m

Indexing: The computed hash code is then used to find the index within the array of buckets. The index is typically obtained by performing a modulo operation on the hash code to ensure it fits within the array size.

Suppose if we have a hashtable of size 7 then

hashcode(key) = key%7

Collisions: Collisions occur when two or more keys produce the same hash code and hence map to the same bucket. To handle collisions, Java’s HashMap uses a concept called chaining. Each bucket contains a linked list (or a balanced tree in later Java 8 versions) of key-value pairs that have the same hash code.

Insertion and Retrieval: When you insert a key-value pair, the HashMap checks if there is already an entry in the bucket corresponding to the computed index or not. If there is not entry then add a new entry to the bucket. If collision occurs, the newly given entry will be added to the existing linked list (or tree) within the bucket. When you retrieve a value by its key, the HashMap uses the hash code to find the correct bucket. If bucket found then it searches through the linked list (or tree) within that bucket to locate the desired key-value pair.

Resizing: To maintain efficiency, the HashMap dynamically resizes its array of buckets when the number of entries crosses a certain threshold. This helps prevent too many collisions and ensures that the average number of entries per bucket remains relatively low.

Example of Hashmap

import java.util.HashMap;
public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();

        hashMap.put("java", 1);
        hashMap.put("python", 2);
        hashMap.put("html", 3);

        int javaValue = hashMap.get("java");
        System.out.println("Value of 'java': " + javaValue); 

        boolean containsKey = hashMap.containsKey("python");
        System.out.println("Contains 'python': " + containsKey);  

        hashMap.remove("html");
        System.out.println("Size of HashMap: " + hashMap.size());  
    }
}

Output

Value of 'java': 1
Contains 'python': true
Size of HashMap: 2

Q4). Explain how hashcode will be calculated for String Key.

Ans:

Hashmap has hashCode() method. This method is used to calculate the hashcode value of the String as an Integer.

Syntax of hascode:

public int hashCode()

Program

import java.io.*; 
class Main {
public static void main(String[] args)
{
  String str = "Name";
  System.out.println(str);
  int hashCode = str.hashCode();
  System.out.println(hashCode);
 }
}

Output

Name
2420395

Here we got Output 2420395 for String “Name”. Below is the way to calculate the hashcode of the string.

How hashcode is calculated for string key?

Below  is the formula to calculate the hashcode value of a String:

s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

Here:

  • s[i] is the ith character of the string
  • ^ is a the exponential operator
  • n shows the length of the string

Q5). What is the Difference between HashMap and LinkedHashMap?

Ans:

  • The difference between HashMap and LinkedHashMap is that LinkedHashMap maintains the insertion order of keys but HashMap doesn’t maintain the insertion order of keys.
  • LinkedHashMap requires more memory than HashMap to keep the record of the insertion order. Basically, LinkedHashMap uses doubly LinkedList to keep track of the insertion order of keys.
  • LinkedHashMap extends HashMap and implements the Map interface and Hashmap extends AbstractMap class and implements the Map interface.
  • Hashmap was introduced in JDK 2.0 but LinkedHashMap was introduced in JDK 4.0.

Here is the Program of HashMap and LinkedHashMap.

Program on Hashmap

import java.util.HashMap;
public class Main {
public static void main(String[] args)
{
  HashMap<String,String> map = new HashMap<>();
  map.put("firstName","Interview");
  map.put("lastName","Expert");
  map.put("rollNo","1");
  System.out.println(map.size());
  if(map.containsKey("firstName")){
    System.out.println(map.get("firstName"));
  }
  if(Integer.parseInt(map.get("rollNo"))<20){
    System.out.println(map.get("lastName"));
  } 
 }
}

Output:

3

Interview

Expert

Program Of LinkedHashMap:

import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args)
{
  LinkedHashMap<String,String> map = new LinkedHashMap<>();
  map.put("firstName","Interview");
  map.put("lastName","Expert");
  map.put("rollNo","1");
  System.out.println(map.size());
  if(map.containsKey("firstName")){
    System.out.println(map.get("firstName"));
  }
  if(Integer.parseInt(map.get("rollNo"))<10){
    System.out.println(map.get("lastName"));
  } 
 }
}

Output:

3

Interview

Expert

Q6). What is Concurrent HashMap?

Ans:

ConcurrentHashMap is a class of Collection Framework that provides a concurrent version of HashMap. It is a thread-safe i.e. multiple threads can access the single object of the map.

At a time any number of threads can perform the read operations without locking. But for write/update operation at a single time thread must lock the particular segment in which the thread wants to operate.

Functionality wise HashMap and ConcurrentHashMap are the same, except ConcurrentHashMap maintains concurrency. Hashmap Can have a null key and value but concurrentHashMap Cannot have null key and value pair.

ConcurrentHashMap uses a Hashtable data structure. 

ConcurrentHashMap Example

import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args)
{
  Map<String,String> chm = new ConcurrentHashMap<>();
  chm.put(null,null);
}
}

Output

Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
at Main.main(Main.java:7)

Here we will get a NullPointerException because we are trying to insert a null key value in the concurrent hashmap which is not allowed.

Q7). What is the Time Complexity of HashMap?

Ans : 

Usually, Time complexity of the Hashmap is O(1). But in some cases, it might change. Let’s assume a scenario in the hashmap when the hashcode will return the same index value for each entries. In that case at a single index of the hashtable, a singly linked list will create to store the key-value pair of the hashmap.

This is a worst-case scenario in HashMap which will be O(n) complexity to lookup. Here we have to walk through all entries in the same hash bucket. This situation is very rare.

There are some improvements done in Java 8 to improve the time complexity from O(n) to O(log n). Instead of using singly linked list, Hashmap in Java 8 uses self-balancing tree like RB tree and AVL tree.

Q8) Tell me some differences between ArrayList and LinkedList.

Ans:

  • ArrayList uses a dynamic array/Array object data structure to store the elements but LinkedList internally uses a doubly linked list to store the elements. 
  • ArrayList Manipulation is slow because it uses an array and if we remove any element from the array we have to shift other elements in memory. But LinkedList Manipulation is faster because it uses a doubly linked list so no shift is required when we remove any element.
  • ArrayList is better for storing and accessing elements but LinkedList is better for manipulating elements.
  • ArrayList takes memory in a contiguous fashion but the linked list does not takes memory in a contiguous.

Q9) When you will prefer ArrayList and when LinkedList in your RealTime projects?

Ans:

As We know Accessing an element in ArrayList takes constant time [O(1)] and adding an element takes O(n) in the worst case. And in LinkedList inserting an element takes O(n) time and accessing also takes O(n) time but LinkedList needs some more memory than ArrayList.

Accessing elements in ArrayList is faster because it is index based. But Accessing elements in LinkedList is slower because we need to traverse each node. Insertion and deletion in Linked List are much faster because here we need to change the pointer of the node only. We need not shift the element as we do in ArrayList. 

So here we are at the conclusion, if we need to perform more manipulation work on the element and memory is not a problem then we can prefer Linked List over ArrayList.

But When we require more searching of the element then we can choose ArrayList over LinkedList.

Time complexity with operations

 For ArrayList<E>

  • get(int index) takes O(1).
  • add(E element) operation takes O(1) amortized, but in the worst case it will be O(n) since the array must be resized and copied.
  • add(int index, E element) takes O(n) Complexity (with n/2 steps on average).
  • remove(int index) operation takes O(n) (with n/2 steps on average).
  • Iterator.remove() have O(n) Complexity (with n/2 steps on average). 
  • ListIterator.add(E element) operation takes O(n) (with n/2 steps on average)

For LinkedList<E>

  • get(int index) operation takes O(n) , It will take O(1) when index = 0 or index = list.size() -1 .
  • add(int index, E element) take O(n) and It will take O(1) when index = 0 or index = list.size() – 1
  • remove(int index) takes O(n) and It will take O(1) when index = 0 or index = list.size() – 1. 

Q10) What is the difference between HashSet and LinkedHashSet?

Ans:

  • HashSet uses Hashtable to store the elements. LinkedHashSet uses HashTable and a doubly linked list to store and maintain the insertion order of the elements.
  • HashSet extends AbstractSet class but LinkedHashSet extends HashSet.
  • HashSet won’t maintain the insertion order of the element but LinkedHashSet maintains the insertion order of an element.
  • HashSet takes less memory in comparison to LinkedHashSet because HashSet won’t maintain the insertion order but LinkedHashSet maintains the insertion order.
  • HashSet provides faster performance than LinkedHashSet.

Q11) Differences between HashMap and HashSet.

Ans:

  • Hashmap is the implementation of the Map interface But HashSet is the implementation of the Set interface.
  • HashSet internally uses Hashmap for its implementation But HashMap Won’t.
  • HashMap stores value in key-value pair But HashSet Stores only object no key-value pair.
  • HashMap uses the put(k,v) method to add elements to the map whereas HashSet uses add(K) method.
  • HashMap Allows duplicate values not key But HashSet won’t allow duplicate values.
  • HashMap allows a single null key and multiple null values but HashSet allow only one null value.

Multi-threading Questions

Q12) What are the Different ways to create threads in Java?

Ans:

There are two ways to create threads in Java:

  1. By extending the Thread class
  2. By implementing a Runnable interface.

1). By Extending the Thread Class

class Main extends Thread{  
    public void run(){  
        System.out.println("thread is running");  
    }  
    public static void main(String args[]){  
        Main thread1 = new Main();  
        thread1.start();  
    }  
} 

Output:

Thread is running

2). By implementing a Runnable interface

class Main implements Runnable{  
  public void run(){  
    System.out.println("thread is running");  
  }    
  public static void main(String args[]){  
    Main obj=new Main();  
    // Here we are Using the constructor Thread(Runnable r)
    Thread tobj =new Thread(obj);     
    tobj.start();  
  }  
}  

Output:

Thread is running

Q13). Difference between Thread and Runnable.

Ans:

  • Thread is a class used to create a thread Whereas Runnable is an interface that is used to create a thread.
  • Thread has methods like start() and run() but Runnable has only one method run().
  • Thread won’t allow multiple inheritance but Runnable allows multiple inheritance.
  • Thread requires more memory but Runnable requires less memory.
  • In Thread Each thread creates a unique object but in Runnable same object is shared with multiple threads.

Q14) Tell some Differences between Callable & Runnable in Java.

Ans: 

  • Callable belongs to java.util.concurrent package whereas Runnable belongs to java.lang package.
  • Thread will not create by passing a callable as a parameter but Runnable will create a thread by passing a runnable as a parameter.
  • Callable has call() method whereas Runnable has the run() method.
  • Callable might return some output but Runnable does not return anything.
  • By invoking invokeAll() method bulk execution of the task is possible in callable but in runnable we can’t use it for bulk execution of the task.

Q15). What is the difference between sleep() & wait() methods in Java.

Ans:

  • Sleep() method belongs to the Thread class whereas Wait() method belongs to the Object class.
  • Sleep() method is used to pause the execution of the current thread for a given time in Milliseconds. But the wait() method tells the thread to wait until another thread invoke’s the notify() or notifyAll() method for this object.
  • Sleep() method will not release the lock on the object during Synchronization but Wait() method can release the lock on the object during Synchronization.
  • Sleep() is a static method but wait() is not a static method.
  • Sleep() has two overloaded methods sleep(long millis) and sleep(long millis, int nanos), Whereas Wait() has Three Overloaded methods wait(), wait(long timeout), wait(long timeout, int nanos).

Example of Sleep method

import java.lang.Thread;
class Main {
    public static void main(String[] args)
    {
        try {
            for (int i = 1; i <=10; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output

1
2
3
4
5
6
7
8
9
10

Exceptional Handling in Java

Q16). What is Exceptional Handling in Java?

Ans:

In Java, Exception Handling ismechanism to handle runtime errors and protect the program from abnormal termination. It helps to maintain the normal flow of the application in case any exceptions come.

There are multiple types of Exceptions such as ClassNotFoundException, IOException, and SQLException.

java.lang.Throwable class is the root class of the Java Exception hierarchy. It is inherited by two subclasses Exception and Error. The hierarchy of Java Exception classes is given below:

java interview question for mncs experienced

Q17). Difference between Checked and Unchecked Exceptions.

Ans: 

  • Checked exception occurs at compile time whereas the Unchecked exception occurs at run time.
  • Checked Exception is checked by the compiler but the Unchecked exception is not.
  • Checked Exception can be handled at compile time but Unchecked Exception can be handled at runtime.
  • Checked Exception is a sub-class of the Exception class but Unchecked Exception is not a part of the Exception class.
  • Some Checked Exceptions are ClassNotFoundException, IOException, SQLException, etc. Some Unchecked Exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundExceptions.
java interview questions for experienced

Q18). How many ways you can print exceptions in Java?

Ans:

There are multiple ways to print the exceptions in Java. Here we will see 3 methods to print the exceptions.

1). printStackTrace()

2). toString()

3). getMessage()

1). printStackTrace()

printStackTrace method prints exception information printStackTrace() is a method of Java.lang.Throwable class. It is used to print the details of exceptions like class name and line number where the exception occurred.

Program to demonstrate printStackTrace() method

import java.io.*;
class Main {
    public static void main (String[] args) {
      int a=5, b=0;
        try{
          System.out.println(a/b);
        }
        catch(ArithmeticException e){
          e.printStackTrace();
        }
    }
}

Output:

java.lang.ArithmeticException: / by zero

at Main.main(Main.java:6)

2). toString() 

toString() method is also used to print exceptions. It prints exception information in the format of Name of the exception along with a description of the exception.

Program to demonstrate toString() method

import java.io.*;
class Main {
    public static void main (String[] args) {
      int a=5, b=0;
        try{
          System.out.println(a/b);
        }
        catch(ArithmeticException e){
            System.out.println(e.toString());
        }
    }
}

Output:

java.lang.ArithmeticException: / by zero

3). getMessage()

getMessage() method prints only the description of the exception message.

Program to demonstrate  getMessage() method

import java.io.*;
class Main {
    public static void main (String[] args) {
      int a=5, b=0;
        try{
          System.out.println(a/b);
        }
        catch(ArithmeticException e){
            System.out.println(e.getMessage());
        }
    }
}

Output:

/ by zero

Q19). What is the process to create custom Exception in Java?

Ans: Here we are showing two examples to show how you can create your own custom exception class in Java. 

Program 1: Create Custome Exception

class CustomException extends Exception{
    public CustomException(String ex){
        super(ex);
    }
}

public class Main{
    public static void main(String ...a){
        int age = 13;
        try{
            if(age<18){
                throw new CustomException("no valid Age");
            }else{
                System.out.println("Age is valid");
            }
        }
        catch(CustomException e){
             System.out.println("Exception occured: " + e); 
        }
        System.out.println("Rest Code is running"); 
    }
}

Output

Exception occured: CustomException: no valid Age
Rest Code is running

Program 2: Create Custome Exception

class CustomException extends Exception {
   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class Main {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is CustomException");
      } catch(CustomException e) {
         System.out.println(e);
      }
   }
}

Output

Custom Exception Occurred : This is CustomException

Q20). Write the difference between Throw Vs Throws.

Ans:

  • throw keyword is used inside the function or the block of code to throw an exception explicitly when an exception occurs. Whereas throws keyword is used with method signature with exception means exception might be thrown by the function during the execution if an exception occurs.
  • throw keyword is followed by an instance of Exception that will be thrown whereas throws keyword is followed by class names of Exceptions to be thrown.
  • throw keyword can be used to throw only one exception at a time but in throws keywords, we can use multiple Exception classes separated by a comma.
  • throw keyword is used to propagate unchecked Exceptions whereas the throws keyword is used to propagate checked Exceptions.

Program of using throw keyword

public class Main{
   public void checkAge(int age){
      if(age<18)
         throw new ArithmeticException("Age is not valid for voting");
      else
         System.out.println("Age is valid for voting");
   }
   public static void main(String args[]){
      Main obj = new Main();
      obj.checkAge(10);
      System.out.println("Execution continue");
   }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Age is not valid for voting
at Main.checkAge(Main.java:4)
at Main.main(Main.java:10)

Program of using throws keywords

public class Main{
   public int division(int a, int b) throws ArithmeticException{
      int result = a/b;
      return result;
   }
   public static void main(String args[]){
      Main obj = new Main();
      try{
         System.out.println(obj.division(15,0));
      }
      catch(ArithmeticException e){
         System.out.println("We can't divide number by zero");
      }
   }
}

Output

We can't divide number by zero

Q21). What is Serialization and why do we use it?

Ans:

Serialization is used to convert the object into a byte stream so that it can be sent over the network. Deserialization is the reverse process where the byte stream is converted into an actual Java object. 

Serialization is required because Network infrastructure and Hard disk or any other hardware components can understand bits and bytes only but not the JAVA objects.

So we use Serialization as a translation to translate our Java object’s values/states to bytes to send it over the network or save it.

SerialVersionUID is used here for identity purposesIt must be static, final, and of type long.

Java Program for Serialization and Deserialization 

import java.io.*;
public class Main {
    public static void main(String[] args) {
        Student student = new Student("quescol", 2);
        byte[] bytes = convertObjectToBytes(student);
        System.out.println(bytes);
        Student s = (Student) convertBytesToObject(bytes);
        System.out.println(s);
    }
    public static byte[] convertObjectToBytes(Object obj) {
        ByteArrayOutputStream boas = new ByteArrayOutputStream();
        try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
            ois.writeObject(obj);
            return boas.toByteArray();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        throw new RuntimeException();
    }
    public static Object convertBytesToObject(byte[] bytes) {
        InputStream is = new ByteArrayInputStream(bytes);
        try (ObjectInputStream ois = new ObjectInputStream(is)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException ioe) {
            ioe.printStackTrace();
        }
        throw new RuntimeException();
    }
}

class Student implements Serializable {
    private String name;
    private int age;
    public Student( String name, int id) {  
        this.age = age;  
        this.name = name;  
    }
}

Output

[B@7d4793a8
Student@721e0f4f

Q22). What is the volatile and Transient keyword in Java?

Ans:

  • A volatile keyword is used in a multithreading environment. When two threads are performing reading and writing operations on the same variable, a volatile keyword is used. It flushes the changes directly to the main memory instead of the CPU cache. A transient keyword is used in serialization. Variable where transient is used, cannot be part of the serialization and deserialization.
  • Volatile variable is not initialized with any default value whereas transient variables are initialized with a default value during deserialization.
  • Volatile variable can be used with the final keyword whereas Transient cannot be used with the final keyword.
  • Volatile variable can be used with static keyword whereas Transient cannot be used with the static keyword.

Q23). How you will create an Immutable class in Java?

Ans:
In Java, an Immutable class means once the object is created in the class, its fields cannot be changed or modified. 
All the wrapper classes like Boolean, Byte, Long, Short, Integer, Float, Double, Char, and String are immutable.
There are some steps by following we can create an immutable class in Java

  • First Declare the class with the final keyword so it can’t be extended.
  • Make all the classes private. It will not allow direct access.
  • Don’t make any setter methods for variables.
  • Make all mutable fields final so that their value can be assigned only once.
  • Initialize all fields value using the constructor. 

Program of Immutable Java Class

final class Student{
  private String name;
  private int roll;
  Student(String name, int roll) {
    this.name = name;
    this.roll = roll;
  }
  public String getName() {
    return name;
  }
  public int getRoll() {
    return roll;
  }
}
class Main {
  public static void main(String[] args) {
    Student obj = new Student("quescol", 1);
    System.out.println("Name: " + obj.getName());
    System.out.println("Roll: " + obj.getRoll());
  }
}

Output:

Name: quescol
Roll: 1

Q24). How you will Create a Singleton class in Java.

Ans:

Singleton class is a class in oops that can have only one object at a time and can be globally accessible.

It Saves memory because Only a single instance is created and reused again and again.

Single Class is mostly used in the multi-threaded system, database application, logging, caching, configuration settings, etc.

There are two forms of singleton design pattern

Early Instantiation: In this Singleton design pattern object will create at the load time.

Lazy Instantiation: In this Singleton design pattern object will create according to the requirement.

Early Instantiation Program

class Singlton {
    //Instance will be created at load time  
    private static Singlton obj=new Singlton();
    private Singlton(){}  
    public static Singlton getSinglton(){  
        return obj;  
    }  
}
class Main {
   public static void main(String[] args) {
      Singlton s1;
      s1= Singlton.getSinglton();
      Singlton s2;
      s2= Singlton.getSinglton();
      System.out.println(s1);
      System.out.println(s2);
   }
}

Output

Singlton@1e81f4dc
Singlton@1e81f4dc

Lazy Instantiation example

class Singlton {
    private static Singlton singlton;
    private Singlton(){
        
    }
    public static Singlton getInstance() {
        if(null == singlton){
            singlton = new Singlton();
        }
    return singlton;
    }
}
class Main {
   public static void main(String[] args) {
      Singlton s1;
      s1= Singlton.getInstance();
      Singlton s2;
      s2= Singlton.getInstance();
      System.out.println(s1);
      System.out.println(s2);
   }
}

Output

Singlton@3b22cdd0

Singlton@3b22cdd0