Latest Java Interview Questions : Core Java, Multithreading, Design Patterns, Collections

OOPs Concepts – In this tutorial, we will learn about Core Java, Java Basics, Oops Concepts, Static Members, String Concept etc.

OOPs Concepts Overview

Question 1: What is an object and what are three characteristics of an object?
Answer: An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: an object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

Question 2: What is meant by encapsulation in java?
Answer: Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. S.t. Declare the variables of a class as private. Provide public setter and getter methods to modify and view the variables values.

Questions 3: What is meant by Inheritance in java? Does Java support multiple inheritances?
Answer: Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Java doesn’t allow multiple inheritance due to diamond problem (is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C).

Question 4: What is meant by Polymorphism in java?
Answer: Polymorphism is the ability of an object to take on many forms.
Polymorphism is an important concept of object-oriented programming. It simply means more than one form. That is, the same entity (method or operator or object) behaves differently in different scenarios. For example,

The + operator in Java is used to perform two specific functions. When it is used with numbers (integers and floating-point numbers), it performs addition.

int a = 5;
int b = 6;
int sum = a + b; // Output = 11

And when we use + operator with strings, it performs string concatenation. For example,

String firstName = "abc ";
String lastName = "xyz";
name = firstName + lastName;     //  Output = abc xyz1

Types of Polymorphism

In Java, Polymorphism can be divided into two types:

Run-time Polymorphism – In Java, run-time polymorphism can be achieved through method overriding.
Compile-time Polymorphism – The compile-time polymorphism can be achieved through method overloading and operator overloading in Java.

Java Method Overloading Vs Method Overriding
In the case of method overriding, methods should be inside different classes. Whereas, in the case of method overloading, methods should be inside the same class.
Method overriding is performed at run-time whereas method overloading is performed at compile-time.

Question 5: What is meant by Abstraction in java?
Answer: Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces.

Question 6: What is the difference between Abstraction and Encapsulation in Java?
Answer: Even though both Abstraction and Encapsulation looks similar because both hide complexity and make the external interface simpler there is a subtle difference between them. Abstraction hides logical complexity while Encapsulation hides Physical Complexity.

Question 7: What is the difference between aggregation and composition?
Answer: Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

Question 8: Is there any difference between nested classes and inner classes?
Answer: Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the part of nested classes.

Question 9: Can a class have an interface?
Answer: Yes, an interface can be defined within the class. It is called a nested interface.

class class_name{
interface nested_interface_name{

Question 10: Can an Interface have a class?
Answer : Yes, they are static implicitly (static nested class).

interface M{
class A{}

Question 11: How many types of exception can occur in a Java program?
Answer: There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:
Checked Exception: Checked exceptions are the one which is checked at compile-time. For example, SQLException, ClassNotFoundException, etc.

Unchecked Exception: Unchecked exceptions are the one which is handled at runtime because they cannot be checked at compile-time. For example, ArithmaticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

Error: Error cause the program to exit since they are not recoverable. For Example, OutOfMemoryError, AssertionError, etc.

Question 12: Difference between checked and unchecked exception?

checked – The compiler checks the checked exception.
unchecked – The compiler does not check the Unchecked exception.

Class of Exception
checked-Except “RuntimeException” class all the child classes of the class “Exception”, and the “Error” class and its child classes are Checked Exception.
unchecked-“RuntimeException” class and its child classes, are”Unchecked Exceptions”.

checked-If we do not handle the checked exception, then the compiler objects.
unchecked-Even if we do not handle the unchecked exception, the compiler doesn’t object.

checked-The program doesn’t compile if there is an unhandled checked exception in the program code.
unchecked-The program compiles successfully even if there unchecked-is an unhandled unchecked exception in the program code.

Question 13: Multiple exception in single catch was introduced in which java version?

Question 14: How can you throw an error from catched exception?
Answer: throws keyword is used to declare that a method may throw one or some exceptions. The caller must catch the exceptions. In your program, you will handle this exception using try & catch. If you do not handle the exception in a try catch block, compiling will fail.

Question 15: What is equals and hashcode contract?
Answer. The contract between equals() and hashCode() is:

1) If two objects are equal, then they must have the same hash code.
2) If two objects have the same hash code, they may or may not be equal. The idea behind a Map is to be able to find an object faster than a linear search.

Question 16: Can we have duplicate keys in Hashmap
Answer. No.

Question 17: If we want to have duplicate keys in Hashmap. How can we achieve that?
Answer. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.

Question 18: What are different types of injection in Spring?

1. Setter Injection-This is the most popular and simple DI method, it will injects the dependency via a setter method. Example. A helper class with a setter method.

  1. Constructor Injection-This DI method will injects the dependency via a constructor. Example. A helper class with a constructor.

Question 19: What is circular dependency?
I have the following classes.

public class B 
    public A a;

    public B()
        a= new A();
        System.out.println("Creating B");

public class A 
    public B b;

    public A()
        b = new B();
        System.out.println("Creating A");

    public static void main(String[] args) 
        A a = new A();

As can be clearly seen, there is a circular dependency between the classes. if I try to run class A, I eventually get a StackOverflowError.

Question 20: What is the purpose of the Runtime class?
Java Runtime class is used to interact with a java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. There is only one instance of java.lang.Runtime class is available for one java application. The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Question 21. How will you invoke any external process in Java?
By Runtime.getRuntime().exec(?) method. Consider the following example.

public class Runtime1{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("notepad");//will open a new notepad

Question 22: Can you access the private method from outside the class?
Yes, by changing the runtime behavior of a class if the class is not secured

Question 23: Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. In unicode, character holds 2 byte, so java also uses 2 byte for characters. The \u0000 is the lowest range of Unicode system.

Question 24: What if the main() method is declared as private? What happens when the static modifier is removed from the signature of the main() method?
When the main() method is declared as private, the program compiles but during runtime it shows “main() method not public.” message.
When the static modifier is removed from the signature of the main() method, the Program compiles but at runtime throws an error “NoSuchMethodError”.

Question 25: How to find if JVM is 32 or 64 bit from Java program. ?
You can find JVM – 32 bit or 64 bit by using System.getProperty() from Java program.

Question 26: What is Garbage Collection and what are its advantages? Are there any disadvantages of Garbage Collection?
Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. Yes, Whenever the garbage collector runs, it has an effect on the application’s performance. This is because all other threads in the application have to be stopped to allow the garbage collector thread to effectively do its work.

Question 27: When does an object become eligible for garbage collection? Describe how the GC collects an eligible object?
An object becomes eligible for Garbage collection or GC if it is not reachable from any live threads or by any static references.

Question 28: Describe what happens when an object is created in Java ?

  1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
  2. The instance variables of the objects are initialized to their default values.
  3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
    as java.lang.Object is the base class for all objects in java.
  4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Question 29: Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains will complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Question 30: Different types of memory used by JVM ?
Class, Heap, Stack, Register, Native Method Stack.

Question 31: Difference between static vs. dynamic class loading?

static loading – Classes are statically loaded with Java’s “new” operator.
dynamic class loading – Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Class.forName (Test className);

Question 32: What is PermGen or Permanent Generation and metaspace ?
The memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.
The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.

Question 33: What is ClassLoader in Java?
This was one of advanced question few years ago, but in span of two to three years, this has become very common. When a Java program is converted into .class file by Java compiler which is collection of byte code class loader is responsible to load that class file from the file system,network or any other location. This class loader is nothing but also a class from which location they are loading the class according to that class loaders are three types :
3.System class loader

Question 34: Can you access a non-static variable in the static context?
Another tricky Java question of Java fundamentals. No, you cannot access a non-static variable from the static context in Java. If you try, it will give compile time error.

Question 35: Why String is Immutable or Final in Java?
The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect all other clients.

Question 36: Why character array is better than String for Storing password in Java?
Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat.

Question 37: What is term synchronization in java?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

Question 38: Can we instantiate Abstract class?
We can not create object for abstract class directly. but indirectly through sub class object we can achieve it.

Question 39: When a class should be defined as final?

If we do not want to allow subclasses.
If we do not want to extend the functionality.

Question 40: What is the difference between StringBuffer and StringBuilder in Java?
StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not synchronized.Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer.

Question 41: Difference between Hashtable and ConcurrentHashMap in Java?
Both Hashtable and ConcurrentHashMap is used in multi-threaded environment because both are therad-safe, but main difference is on performance Hashtable’s performance become poor if the size of Hashtable become large because it will be locked for long time during iteration, but in case of concurrent HaspMap only specific part is locked because concurrent HaspMap works on segmentation and other thread can access the element without iteration to complete.

Question 42: What is the difference between HashSet and TreeSet?
Both HashSet and TreeSet classes implement the Set interface and represent sets of distinct elements. Additionally, TreeSet implements the NavigableSet interface. This interface defines methods that take advantage of the ordering of elements.

Question 43: What is the performance effect of a large number of import statements which are not used?
They are ignored if the corresponding class is not used.

Question 44: What will happen if an exception is thrown from the finally block?
The program will exit if the exception is not catched in the finally block.

Question 45: How does decorator design pattern works in I/O classes?
The various classes like BufferedReader, BufferedWriter work on the underlying stream classes. Thus Buffered* class will provide a Buffer for Reader/Writer classes.

Question 46: If I give you an assignment to design Shopping cart web application, how will you define the architecture of this application. You are free to choose any framework, tool or server?
Usually I will choose a MVC framework which will make me use other design patterns like Front Controller, Business Delegate, Service Locater, DAO, DTO, Loose Coupling etc. Struts 2 is very easy to configure and comes with other plugins like Tiles, Velocity and Validator etc. The architecture of Struts becomes the architecture of my application with various actions and corresponding JSP pages in place.

Question 47: What is a deadlock in Java? How will you detect and get rid of deadlocks?
Deadlock exists when two threads try to get hold of a object which is already held by another object.

Question 48: Why is it better to use hibernate than JDBC for database interaction in various Java applications?
Hibernate provides an OO view of the database by mapping the various classes to the database tables. This helps in thinking in terms of the OO language then in RDBMS terms and hence increases productivity.

Question 49: How can one call one constructor from another constructor in a class?
Use the this() method to refer to constructors.

Question 50: What is the purpose of intern() method in the String class?
It helps in moving the normal string objects to move to the String literal pool.

Question 51: How will you make your web application to use the https protocol?
This has more to do with the particular server being used than the application itself.

Question 52: You have thread T1, T2, and T3. How will you ensure that thread T2 is run after T1 and thread T3 after T2?
Answer. It is to check whether the candidate is familiar with the concept of “join” method or not. The answer to this multi-threading question is simple — it can be achieved by using the join method of Thread class.

Question 53: What are differences between wait and sleep method in Java?
The only major difference is to wait to release the lock or monitor, while sleep doesn’t release any lock or monitor while waiting.

Question 54: Why wait and notify is declared in Object class instead of Thread ?
Well These methods should be in object class because Thread can call these methods on any JAVA OBJECT.

Question 55: How to detect a deadlock condition? How can it be avoided?
We can detect the deadlock condition by running the code on cmd and collecting the Thread Dump, and if any deadlock is present in the code, then a message will appear on cmd.
Ways to avoid the deadlock condition in Java:
Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock occurs when we provide locks to various threads so we should give one lock to only one thread at some particular time.
Avoid unnecessary locks: we must avoid the locks which are not required.
Using thread join: Thread join helps to wait for a thread until another thread doesn’t finish its execution so we can avoid deadlock by maximum use of join method.

Question 56: What is race-condition?
A Race condition is a problem which occurs in the multithreaded programming when various threads execute simultaneously accesses a shared resource at the same time. The proper use of synchronization can avoid the Race condition.

Question 57: What do you understand by Java virtual machine?
Answer. Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification that must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode that is machine-independent and close to the native code.

Question 58: What is the difference between JDK, JRE, and JVM?
Answer. JVM is an acronym for Java Virtual Machine; it is an abstract machine that provides the runtime environment in which Java bytecode can be executed. It is a specification that specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform-dependent). It is a runtime instance that is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools that are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment that is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
1)Standard Edition Java Platform
2)Enterprise Edition Java Platform
3)Micro Edition Java Platform

Question 59: How many types of memory areas are allocated by JVM?
1) Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
2) Heap: It is the runtime data area in which the memory is allocated to the objects.
3) Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
4) Program Counter Register: The PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
5) Native Method Stack: It contains all the native methods used in the application.

Question 60: What is the platform?
Answer. A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides a software-based platform.

Question 61: What are the main features of Java?
1) Object-Oriented programming language
2) Simple
3) Distributed
4) Multithread
5) Platform Independent
6) Secured
7) Portable
8) Robust
9) Architectural Neutral

Question 62: Is it possible to declare an Array without Array size?
Answer. It is not possible to declare an Array without Array size. If you try to do so then you will get a compile-time error.

Question 63: What if I write static public void instead of public static void?
Answer. The program compiles and runs correctly because the order of specifiers don’t matter in Java.

Question 64: What is the default value of the local variables?
Answer. The local variables are not initialized to any default value, neither primitives nor object references.

Question 65: What is the difference between constructor and method in java?
The constructor is the special member of the class with the same name as the class and no return type. But the method is the ordinary member of a class used to describe the behavior of some object or class.

Question 66: Is it possible to overload the main() method?
Yes, the main method can be overloaded. But we should declare the original one like public static void main(String args[]){} because JVM will look for this when starting execution.

Question 67: Does the constructor return any value?
Yes, The constructor implicitly returns the current instance of the class.

Question 68: Can you make a constructor final?
No, the constructor can’t be final.

Question 69: Why is the main method static?
Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation.

Question 70: What are the various access specifiers in Java?
In Java, access specifiers are the keywords that are used to define the access scope of the method, class, or variable. In Java, there are four access specifiers given below.
1) public: The classes, methods, or variables which are defined as public, can be accessed by any class or method.
2) protected: protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
3) default: default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
4) private: The private class, methods, or variables defined as private can be accessed within the class only.

Have a great day 🙂