Java interview questions
Prepare for your Java interview with these common questions and answers.
01What is the difference between JDK, JRE, and JVM?
JVM (Java Virtual Machine) is an abstract machine that provides a runtime environment to execute Java bytecode.
JRE (Java Runtime Environment) is a set of software tools for developing Java applications. It contains the JVM, class libraries, and other supporting files.
JDK (Java Development Kit) is a software development environment used for developing Java applications and applets. It includes the JRE, a compiler (javac), a debugger, and other development tools.
02What are the main principles of Object-Oriented Programming (OOP)?
The four main principles of OOP are:
- Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit or class.
- Inheritance: A mechanism where a new class inherits properties and behavior from an existing class.
- Polymorphism: The ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
- Abstraction: Hiding complex implementation details and showing only the necessary features of an object.
03What is the difference between `==` and `.equals()`?
The == operator is a reference comparison, i.e., it checks if both objects point to the same memory location.
The .equals() method is a content comparison. It evaluates the comparison of values in the objects. If not overridden in a class, the default implementation from the Object class uses ==.
04What is method overloading vs. method overriding?
Method Overloading: Occurs when two or more methods in the same class have the same name but different parameters (different number, type, or order of parameters). It's a compile-time polymorphism.
Method Overriding: Occurs when a subclass has a method with the same name, parameters, and return type as a method in its superclass. It's a run-time polymorphism.
05What is a constructor? Can a constructor be private?
A constructor is a special method used to initialize objects. It is called when an instance of the class is created. Yes, a constructor can be private. This is often used in the Singleton design pattern to ensure that only one instance of a class can be created.
06What is the `final` keyword in Java?
The final keyword can be used with variables, methods, and classes.
- final variable: The value cannot be changed. It's a constant.
- final method: Cannot be overridden by a subclass.
- final class: Cannot be inherited.
07What is the `static` keyword in Java?
The static keyword is used for memory management mainly. It can be applied to variables, methods, blocks, and nested classes.
- static variable: Belongs to the class rather than an instance of the class. There's only one copy.
- static method: Belongs to the class and can be called without creating an instance. It can only access static data.
08What is an abstract class?
An abstract class is a class that cannot be instantiated on its own and must be subclassed. It can have both abstract methods (methods without a body) and concrete methods (regular methods with a body).
09What is an interface?
An interface is a completely abstract class that can only contain abstract methods. Since Java 8, interfaces can also have default and static methods with implementations.
10What is the difference between an abstract class and an interface?
Abstract classes can have constructors, instance variables, and concrete methods. A class can extend only one abstract class.
Interfaces can only have abstract methods (and default/static methods since Java 8) and public static final constants. A class can implement multiple interfaces.
11What is exception handling?
Exception handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, etc. It uses try, catch, throw, throws, and finally blocks.
12What is the difference between checked and unchecked exceptions?
Checked Exceptions: Are checked at compile-time. They are subclasses of Exception (excluding RuntimeException). The programmer must handle these exceptions using try-catch or declare them with throws.
Unchecked Exceptions: Are not checked at compile-time. They are subclasses of RuntimeException. It's not mandatory to handle them.
13What is the `finally` block?
The finally block is used to execute important code such as closing a connection, stream, etc. The finally block is always executed whether an exception is handled or not.
14What is the Collections Framework?
The Collections Framework provides an architecture to store and manipulate a group of objects. It includes interfaces (like List, Set, Queue), classes (like ArrayList, HashSet, LinkedList), and algorithms.
15What is the difference between ArrayList and LinkedList?
ArrayList: Uses a dynamic array. Better for storing and accessing data (get and set).
LinkedList: Uses a doubly linked list. Better for manipulating data (add and remove).
16What is the difference between HashMap and Hashtable?
HashMap: Is not synchronized (not thread-safe). Allows one null key and multiple null values.
Hashtable: Is synchronized (thread-safe). Does not allow any null key or value.
17What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. It helps in achieving multitasking.
18How do you create a thread in Java?
There are two ways to create a thread:
1. By extending the Thread class.
2. By implementing the Runnable interface.
19What is synchronization?
Synchronization is the capability to control the access of multiple threads to any shared resource. It's a way to prevent thread interference and consistency problems. It can be achieved using the synchronized keyword or synchronized blocks.
20What are some new features in Java 8?
Key features include:
- Lambda Expressions
- Stream API for collection manipulation
forEach()method in Iterable interface- Default and static methods in Interfaces
- Optional class to handle null values
21What is a String Pool?
String Pool (or String Constant Pool) is a special storage area in the Java heap. When a string is created using literals (e.g., String s = "abc"), the JVM checks if the string already exists in the pool. If it does, it returns a reference to the pooled instance.
22Why are strings immutable in Java?
Strings are immutable for several reasons:
- Security: String parameters are often used for network connections, database URLs, etc. Immutability prevents them from being changed.
- Synchronization: Being immutable makes them inherently thread-safe.
- Caching: The String pool is possible because strings are immutable.
23What is the `this` keyword?
this is a reference variable that refers to the current object. It can be used to refer to the current class instance variable, invoke the current class method, or invoke the current class constructor.
24What is the `super` keyword?
super is a reference variable that is used to refer to the immediate parent class object. It can be used to invoke the parent class method or constructor.
25What is Garbage Collection?
Garbage Collection is the process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. The System.gc() method can be used to trigger the garbage collector.
26What is serialization?
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process. It is used to persist the object or transfer it over a network.
27What is a Singleton class?
A Singleton class is a class that can have only one object (an instance of the class) at a time. This is achieved by making the constructor private and providing a static method that returns the instance.
28What is the difference between fail-fast and fail-safe iterators?
Fail-fast: Throws a ConcurrentModificationException if a collection is modified while iterating over it. Example: ArrayList iterator.
Fail-safe: Doesn't throw an exception. They operate on a clone of the collection. Example: CopyOnWriteArrayList iterator.
29What are Generics in Java?
Generics provide type-safety to your code by allowing you to create classes, interfaces, and methods that can work with different data types while providing compile-time type checking.
30Explain `public static void main(String[] args)`.
- public: It is an access modifier, which specifies from where and who can access the method.
- static: It is a keyword that identifies it is class-based.
main()is made static so that it can be accessed without creating an instance of a class. - void: It is the return type of the method.
voiddefines the method which will not return any value. - main: It is the name of the method which is searched by JVM as a starting point for an application.
- String[] args: It is the parameter passed to the main method.
Preparing for a role?
Tell us what you’re aiming for. A mentor can help you close the gaps before the interview.