[2022] Selected Java Interview Question For Experienced MNCs

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 classes in java which implementation is based on the hash table data structure. HashMap class extends AbstractMap class and AbstractMap  class implements the Map interface.

Some Important point about Hashmap:

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

Q2). What is 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 HashMap Internally works in Java?

Ans:

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 hashcode of 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 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 were introduced in JDK 2.0 but LinkedHashMap introduced in JDK 4.0.

Here is the Program of HashMap and LinkedHashMap.

Example of 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

Example 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. Functionality wise HashMap and ConcurrentHashMap are same, except ConcurrentHashMap  maintain concurrency. Hashmap Can have null key and value but concurrentHashMap Cannot have null key and value pair.

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 an NullPointerException because we are trying to insert null key value in concurrent hashmap which is not allowed.

Q7). What is the Time Complexity of HashMap.

Ans : 

Usually Time complexity of Hashmap is O(1). But in some cases it might change. Let’s assume a scenario in hashmap when hashcode will return same index value for each enteries. In that case at single index of hashtable, a singly linked list will create to store the key value pair of 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 compelxity 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 difference between ArrayList and LinkedList.

Ans:

  • ArrayList uses a dynamic array 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 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 is the Different ways to create threads in java?

Ans:

There are two ways to create threads in Java:

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

1). By Extending Thread Class

Output:

Thread is running

2). By implementing Runnable interface

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 Difference 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 callable as a parameter but Runnable will create a thread by passing runnable as a parameter.
  • Callable has call() method whereas Runnable has 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() method 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

Exceptional Handling in Java

Q16). What is exceptional handling in java?

Ans:

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

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

java.lang.Throwable class is the root class of 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

Output:

java.lang.ArithmeticException: / by zero

at Main.main(Main.java:6)

2. toString() 

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

Program to demonstrate toString() method

Output:

java.lang.ArithmeticException: / by zero

 

3. getMessage()

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

Program to demonstrate  getMessage() method

 

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 you own custom exception class in Java.
 
Example 1:
 

Output

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

 

Example 2:

 

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.

Example of using throw keyword

 

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)

Example of using throws keywords

 

Output
We can’t divide number by zero

Q21). What is Serialization and why 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 purposeIt must be static, final, and of type long.

Java Program for Serialization and Deserialization 

 

Output

[[email protected]
[email protected]

Q22). What is 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 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 the all fields value using the constructor. 
Example of Immutable java Class  

Q24). How you will Create 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 Example

 

Output

[email protected]

[email protected]

Lazy Instantiation example

 

Output

[email protected]

[email protected]