Top 100 Java Interview Questions (With Answers): From Basic to Advanced

Abhishek Sur
17 min readJul 25, 2024

--

Java is one of the most popular programming languages and is widely used for developing robust, secure, and scalable applications. If you’re preparing for a Java interview, having a solid understanding of the language’s core concepts and advanced features is crucial. Here’s a comprehensive list of the top 100 Java interview questions and answers to help you get ready.

Basic Level

1. What is Java?

Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It allows developers to write code once and run it anywhere, as long as the platform supports Java.

2. What are the features of Java?

  • Simple: Java is easy to learn and use.
  • Object-Oriented: Everything in Java is treated as an object.
  • Platform Independent: Java code runs on any platform with a JVM.
  • Secure: Java provides a secure environment through its runtime.
  • Robust: Java emphasizes error checking and runtime checking.
  • Multithreaded: Java supports concurrent execution of two or more threads.
  • Portable: Java bytecode can run on any platform without modification.

3. What is JVM, JRE, and JDK?

  • JVM (Java Virtual Machine): An abstract machine that provides the runtime environment to execute Java bytecode.
  • JRE (Java Runtime Environment): The implementation of the JVM which physically exists. It contains a set of libraries and other files that JVM uses at runtime.
  • JDK (Java Development Kit): A full-featured software development kit for Java, including JRE, an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed for Java development.

4. What are the different types of memory areas allocated by JVM?

  • Method Area: Stores class structures like metadata, the constant runtime pool, and the code for methods.
  • Heap: The runtime data area where objects are allocated.
  • Stack: Stores frames, which hold local variables and partial results, and plays a part in method invocation and return.
  • Program Counter (PC) Register: Contains the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: Contains all the native methods used in the application.

5. What is the difference between JDK, JRE, and JVM?

  • JVM: Provides the runtime environment in which Java bytecode can be executed.
  • JRE: Contains JVM and library classes and other files that JVM uses at runtime.
  • JDK: Contains JRE and development tools (like the compiler and debugger) necessary for Java development.

6. What is the JIT compiler?

Just-In-Time (JIT) compiler is a part of the JVM that optimizes bytecode to machine code at runtime to improve performance. The JIT compiler runs when a method is invoked, converting the bytecode into native machine code to be executed directly by the CPU.

7. What are the main differences between Java and C++?

  • Platform Independence: Java is platform-independent, whereas C++ is platform-dependent.
  • Memory Management: Java has automated garbage collection; C++ requires manual memory management.
  • Multiple Inheritance: Java does not support multiple inheritance directly, whereas C++ does.
  • Pointers: Java does not support pointers explicitly, ensuring more security, whereas C++ uses pointers.
  • Threading: Java has built-in support for multithreading, while C++ relies on libraries for threading.

8. What is the base class of all classes in Java?

The base class of all classes in Java is java.lang.Object. It is the root class from which every class implicitly inherits.

9. What is a class in Java?

A class in Java is a blueprint from which individual objects are created. It can contain fields and methods to define the behavior of an object.

10. What is an object in Java?

An object is an instance of a class. It is created using the new keyword and represents a real-world entity with attributes (fields) and behaviors (methods).

11. What is inheritance in Java?

Inheritance is a mechanism wherein a new class is derived from an existing class. The derived class inherits all the features of the base class and can have additional features of its own. It promotes code reuse and establishes a relationship between classes.

12. What are the different types of inheritance in Java?

  • Single Inheritance: A class inherits from one superclass.
  • Multiple Inheritance: A class inherits from more than one superclass (Java does not support this directly due to the “Diamond Problem”).
  • Multilevel Inheritance: A class inherits from a superclass, which in turn inherits from another superclass.
  • Hierarchical Inheritance: Multiple classes inherit from a single superclass.
  • Hybrid Inheritance: A combination of two or more types of inheritance (Java supports hybrid inheritance through interfaces).

13. What is polymorphism in Java?

Polymorphism allows methods to do different things based on the object it is acting upon. It is of two types:

  • Compile-time polymorphism (method overloading): Method names are the same but parameters are different.
  • Runtime polymorphism (method overriding): Method names and parameters are the same, but the actual method that gets called is determined at runtime based on the object.

14. What is abstraction in Java?

Abstraction is a process of hiding the implementation details and showing only the functionality to the user. It is achieved using abstract classes and interfaces.

15. What is encapsulation in Java?

Encapsulation is the technique of wrapping the data (variables) and code (methods) together as a single unit. It helps protect the data from unauthorized access and modification.

16. What are access modifiers in Java?

Access modifiers define the scope of a class, constructor, variable, method, or data member. There are four types:

  • Default: Accessible only within the same package.
  • Private: Accessible only within the same class.
  • Protected: Accessible within the same package and subclasses.
  • Public: Accessible from any other class.

17. What is an interface in Java?

An interface is a reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to achieve abstraction and multiple inheritance in Java.

18. What is an abstract class in Java?

An abstract class is a class that cannot be instantiated on its own and must be subclassed. It can contain abstract methods (without a body) and concrete methods (with a body). It is used to provide a base for subclasses to build upon.

19. What is the difference between an abstract class and an interface?

  • Abstract Class:
  • Can have both abstract and concrete methods.
  • Can have instance variables.
  • Can provide method implementations.
  • Supports single inheritance.
  • Interface:
  • Can only have abstract methods (until Java 8, which introduced default and static methods).
  • Cannot have instance variables (only constants).
  • Cannot provide method implementations (until Java 8).
  • Supports multiple inheritance.

20. What is the difference between method overloading and method overriding?

  • Method Overloading: Multiple methods in the same class with the same name but different parameters (different type, number, or both).
  • Method Overriding: A method in a subclass has the same name, return type, and parameters as a method in its superclass, allowing the subclass to provide a specific implementation.

Intermediate Level

21. What are Java annotations?

Annotations provide metadata for Java code. They can be applied to classes, methods, variables, parameters, and packages to provide information to the compiler or at runtime.

22. What are lambda expressions in Java?

Lambda expressions, introduced in Java 8, provide a clear and concise way to represent one method interface using an expression. They are used primarily to define the inline implementation of a functional interface.

23. What is the Stream API in Java?

The Stream API, introduced in Java 8, is used to process collections of objects. It provides methods for filtering, mapping, and reducing collections to support functional-style operations on data.

24. What are Java Generics?

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They allow for stronger type checks at compile time and eliminate the need for typecasting.

25. What is the difference between List and Set in Java?

  • List:
  • Allows duplicate elements.
  • Maintains the order of elements.
  • Example implementations: ArrayList, LinkedList.
  • Set:
  • Does not allow duplicate elements.
  • Does not maintain the order of elements.
  • Example implementations: HashSet, LinkedHashSet, TreeSet.

26. What is the difference between HashMap and Hashtable?

  • HashMap:
  • Allows null key and null values.
  • Not synchronized (not thread-safe).
  • Faster performance.
  • Hashtable:
  • Does not allow null key or null values.
  • Synchronized (thread-safe).
  • Slower performance.

27. What are the differences between ArrayList and LinkedList?

  • ArrayList:
  • Implements a resizable array.
  • Provides fast random access.
  • Slower insertion and deletion operations.
  • LinkedList:
  • Implements a doubly-linked list.
  • Provides fast insertion and deletion operations.
  • Slower random access.

28. What is the difference between == and equals() in Java?

  • ==: Used to compare primitive types and references (memory addresses).
  • equals(): Used to compare the values within the objects.

29. What is the significance of the hashCode() method?

The hashCode() method returns an integer value, generated by a hashing algorithm. It is used in conjunction with the equals() method to determine the equality of objects, especially in hash-based collections like HashMap, HashSet, and Hashtable.

30. What is the purpose of the final keyword in Java?

The final keyword is used to restrict the user. It can be used in different contexts:

  • Final Variable: Cannot be changed once initialized.
  • Final Method: Cannot be overridden by subclasses.
  • Final Class: Cannot be subclassed.

31. What is the super keyword in Java?

The super keyword in Java is used to refer to the immediate parent class object. It is used to access parent class methods and constructors.

32. What is the this keyword in Java?

The this keyword is used to refer to the current instance of the class. It can be used to access class variables and methods.

33. What is exception handling in Java?

Exception handling is a mechanism to handle runtime errors, ensuring the normal flow of the application. It is achieved using try, catch, throw, throws, and finally blocks.

34. What are checked and unchecked exceptions?

  • Checked Exceptions: Exceptions that are checked at compile-time. Examples include IOException, SQLException.
  • Unchecked Exceptions: Exceptions that are not checked at compile-time. Examples include NullPointerException, ArrayIndexOutOfBoundsException.

35. What is the difference between throw and throws?

  • throw: Used to explicitly throw an exception.
  • throws: Used in method signatures to declare exceptions that might be thrown by the method.

36. What is the difference between String, StringBuilder, and StringBuffer?

  • String: Immutable sequence of characters.
  • StringBuilder: Mutable sequence of characters, not synchronized.
  • StringBuffer: Mutable sequence of characters, synchronized (thread-safe).

37. What are wrapper classes in Java?

Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. Examples include Integer, Boolean, and Character.

38. What is autoboxing and unboxing in Java?

  • Autoboxing: Automatic conversion of primitive types to their corresponding wrapper classes.
  • Unboxing: Automatic conversion of wrapper class objects to their corresponding primitive types.

39. What is the Java Collections Framework?

The Java Collections Framework is a set of classes and interfaces that implement commonly reusable collection data structures. It includes classes like ArrayList, HashSet, and HashMap.

40. What is the difference between Comparable and Comparator?

  • Comparable: Used to define the natural ordering of objects. It has a single method compareTo().
  • Comparator: Used to define a custom ordering of objects. It has a single method compare().

Advanced Level

41. What is multithreading in Java?

Multithreading is a process of executing multiple threads simultaneously. It is used to perform multiple tasks concurrently, making optimal use of CPU resources.

42. How do you create a thread in Java?

Threads can be created in two ways:

  • Extending the Thread class: Create a new class that extends Thread and overrides the run() method.
  • Implementing the Runnable interface: Create a new class that implements Runnable and implements the run() method. Then, create a Thread object and pass the Runnable object to its constructor.

43. What is the difference between start() and run() methods in Java?

  • start() method: Used to start a new thread, calling the run() method internally.
  • run() method: Contains the code that is executed by the thread.

44. What is synchronization in Java?

Synchronization is a mechanism to control the access of multiple threads to shared resources. It ensures that only one thread can access a resource at a time, preventing data inconsistency.

45. What are the types of synchronization in Java?

  • Process Synchronization: Coordinating the execution of processes to ensure they do not interfere with each other.
  • Thread Synchronization: Coordinating the execution of threads to ensure they do not interfere with each other. Achieved using synchronized methods or blocks.

46. What is a deadlock in Java?

A deadlock is a situation where two or more threads are blocked forever, waiting for each other. It occurs when multiple threads have circular dependencies on a set of synchronized resources.

47. What are the different ways to avoid deadlock in Java?

  • Avoid Nested Locks: Avoid giving locks to multiple threads if they are already holding one.
  • Lock Ordering: Ensure that all threads acquire locks in the same order.
  • Lock Timeout: Specify a timeout for thread locks to prevent indefinite waiting.
  • Deadlock Detection: Implement a mechanism to detect and recover from deadlocks.

48. What is the difference between wait() and sleep() methods in Java?

  • wait(): Causes the current thread to release the lock and wait until another thread invokes notify() or notifyAll().
  • sleep(): Causes the current thread to sleep for a specified period without releasing the lock.

49. What are the different types of garbage collectors in Java?

  • Serial Garbage Collector: Single-threaded garbage collector suitable for single-threaded environments.
  • Parallel Garbage Collector: Uses multiple threads to speed up garbage collection.
  • CMS (Concurrent Mark-Sweep) Garbage Collector: Low-latency garbage collector suitable for applications requiring shorter pause times.
  • G1 (Garbage First) Garbage Collector: Designed for large applications with heap sizes of more than 4GB.

50. What is the volatile keyword in Java?

The volatile keyword is used to indicate that a variable's value will be modified by different threads. It ensures that the value of the volatile variable is always read from and written to the main memory.

51. What is the transient keyword in Java?

The transient keyword is used to indicate that a variable should not be serialized. It is used in serialization to exclude variables from the serialization process.

52. What is the Serializable interface in Java?

The Serializable interface is a marker interface that enables an object to be serialized (converted to a byte stream) and deserialized (reconstructed from a byte stream).

53. What is the Externalizable interface in Java?

The Externalizable interface extends the Serializable interface and provides control over the serialization and deserialization process. It requires the implementation of two methods: writeExternal() and readExternal().

54. What is the difference between Serializable and Externalizable?

  • Serializable: Uses default serialization mechanism. Does not require methods to be implemented.
  • Externalizable: Requires explicit implementation of writeExternal() and readExternal() methods to control serialization.

55. What are the different ways to create an immutable class in Java?

  • Declare the class as final to prevent subclassing.
  • Make all fields private and final.
  • Provide only getter methods for fields.
  • Do not provide setter methods.
  • Ensure that mutable fields are not exposed to the outside world.

56. What is the difference between deep copy and shallow copy?

  • Shallow Copy: Creates a new object and copies the non-static fields of the original object to the new object. The fields of the original object are copied as references.
  • Deep Copy: Creates a new object and recursively copies all objects referenced by the fields of the original object, creating a fully independent clone.

57. What is the singleton design pattern?

The singleton design pattern ensures that a class has only one instance and provides a global point of access to it. It is achieved by making the constructor private and providing a static method to get the instance.

58. What is the factory design pattern?

The factory design pattern provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. It is used to delegate the responsibility of object instantiation to a factory class.

59. What is the builder design pattern?

The builder design pattern is used to construct complex objects step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations.

60. What is the prototype design pattern?

The prototype design pattern is used to create a duplicate object or clone of the current object. It is used when the cost of creating an object is expensive or resource-intensive.

61. What is the observer design pattern?

The observer design pattern defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically. It is used to implement distributed event-handling systems.

62. What is the decorator design pattern?

The decorator design pattern is used to add new functionality to an existing object without altering its structure. It provides a flexible alternative to subclassing for extending functionality.

63. What is the strategy design pattern?

The strategy design pattern defines a family of algorithms and makes them interchangeable. It allows the algorithm to vary independently from the clients that use it.

64. What is the command design pattern?

The command design pattern encapsulates a request as an object, thereby allowing parameterization of clients with different requests, queuing of requests, and logging of the requests. It is used to implement callback functions and undoable operations.

65. What is the adapter design pattern?

The adapter design pattern converts the interface of a class into another interface that the clients expect. It allows classes with incompatible interfaces to work together.

66. What is the bridge design pattern?

The bridge design pattern decouples an abstraction from its implementation, allowing both to vary independently. It is used to separate the abstract elements from the implementation elements.

67. What is the facade design pattern?

The facade design pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use.

68. What is the iterator design pattern?

The iterator design pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It is used to traverse collections like lists, maps, and sets.

69. What is the proxy design pattern?

The proxy design pattern provides a surrogate or placeholder for another object to control access to it. It is used to create a representative object that controls access to another object.

70. What is the composite design pattern?

The composite design pattern composes objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly.

71. What is the template method design pattern?

The template method design pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows subclasses to redefine certain steps of an algorithm without changing the algorithm's structure.

72. What is the chain of responsibility design pattern?

The chain of responsibility design pattern passes a request along a chain of handlers. Each handler can either handle the request or pass it to the next handler in the chain. It is used to decouple the sender of a request from its receiver.

73. What is the memento design pattern?

The memento design pattern provides the ability to restore an object to its previous state (undo via rollback). It captures and externalizes an object's internal state so that it can be restored later.

74. What is the state design pattern?

The state design pattern allows an object to change its behavior when its internal state changes. It appears as if the object has changed its class. It is used to encapsulate the state-based behavior.

75. What is the visitor design pattern?

The visitor design pattern separates an algorithm from an object structure by moving the hierarchy of methods into one object. It allows adding new operations to existing object structures without modifying the structures.

76. What is the interpreter design pattern?

The interpreter design pattern defines a representation of the grammar for a language and provides an interpreter to deal with this grammar. It is used to interpret expressions in a language.

77. What is the flyweight design pattern?

The flyweight design pattern reduces the cost of creating and manipulating a large number of similar objects by sharing objects. It is used to minimize memory usage by sharing as much data as possible with similar objects.

78. What is the mediator design pattern?

The mediator design pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

79. What is the abstract factory design pattern?

The abstract factory design pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is used to create a set of related objects.

80. What is the prototype design pattern?

The prototype design pattern is used to create a duplicate object or clone of the current object. It is used when the cost of creating an object is expensive or resource-intensive.

81. What is the service locator design pattern?

The service locator design pattern is used to locate services using a central registry. It abstracts the complexity of looking up services by providing a simple interface to obtain service instances.

82. What is the data access object (DAO) design pattern?

The data access object (DAO) design pattern provides an abstract interface to some type of database or other persistence mechanism. It separates the data access logic from the business logic.

83. What is the dependency injection design pattern?

The dependency injection design pattern is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. It allows the creation of dependent objects outside of a class and provides those objects to the class in various ways.

84. What is the lazy initialization design pattern?

The lazy initialization design pattern is used to delay the initialization of an object until it is actually needed. It is used to improve performance by avoiding unnecessary computation and memory usage.

85. What is the singleton design pattern?

The singleton design pattern ensures that a class has only one instance and provides a global point of access to it. It is achieved by making the constructor private and providing a static method to get the instance.

86. What is the null object design pattern?

The null object design pattern provides an object with no behavior instead of using null references. It eliminates the need to check for null references and provides a default behavior.

87. What is the object pool design pattern?

The object pool design pattern is used to manage the reuse of expensive-to-create objects. It maintains a pool of reusable objects and provides a way to borrow and return them.

88. What is the publish-subscribe design pattern?

The publish-subscribe design pattern allows components to communicate through a message broker. Publishers send messages to the broker, and subscribers receive messages from the broker. It decouples the sender and receiver.

89. What is the repository design pattern?

The repository design pattern abstracts the data access layer and provides a simple interface to access data. It encapsulates the logic required to access data sources and allows business logic to interact with data sources without knowing their implementation details.

90. What is the DTO (Data Transfer Object) design pattern?

The DTO (Data Transfer Object) design pattern is used to transfer data between different parts of a system or between systems. It is a simple object that carries data without any business logic.

91. What is the value object design pattern?

The value object design pattern represents a simple object that does not have a distinct identity and is immutable. It is used to represent domain concepts as values.

92. What is the aggregate design pattern?

The aggregate design pattern defines a collection of objects that are bound together by a root entity. It ensures consistency and enforces invariants by treating the collection as a single unit.

93. What is the factory method design pattern?

The factory method design pattern defines an interface for creating an object, but lets subclasses alter the type of objects that will be created. It delegates the responsibility of instantiation to subclasses.

94. What is the singleton design pattern?

The singleton design pattern ensures that a class has only one instance and provides a global point of access to it. It is achieved by making the constructor private and providing a static method to get the instance.

95. What is the MVC (Model-View-Controller) design pattern?

The MVC (Model-View-Controller) design pattern separates an application into three main components: Model (data), View (user interface), and Controller (business logic). It decouples the components and allows for independent development, testing, and maintenance.

96. What is the front controller design pattern?

The front controller design pattern provides a centralized entry point for handling requests. It allows for centralized control and coordination of request processing.

97. What is the interceptor design pattern?

The interceptor design pattern provides a way to intercept and modify requests and responses. It is used to implement cross-cutting concerns like logging, security, and transaction management.

98. What is the proxy design pattern?

The proxy design pattern provides a surrogate or placeholder for another object to control access to it. It is used to create a representative object that controls access to another object.

99. What is the composite design pattern?

The composite design pattern composes objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly.

100. What is the adapter design pattern?

The adapter design pattern converts the interface of a class into another interface that the clients expect. It allows classes with incompatible interfaces to work together.

--

--