Skip to content

100 Java interview questions with their answers:

Basic Java Concepts

  1. What are the main features of Java?

    • Answer: Java is platform-independent, object-oriented, secure, multithreaded, and robust, with automatic garbage collection, and a rich API.
  2. Explain the difference between JDK, JRE, and JVM.

    • Answer:
      • JVM (Java Virtual Machine): Executes bytecode and provides a runtime environment.
      • JRE (Java Runtime Environment): Includes JVM and standard libraries to run Java applications.
      • JDK (Java Development Kit): Contains JRE plus tools (compiler, debugger) for Java development.
  3. What is the difference between an abstract class and an interface in Java?

    • Answer:
      • Abstract class: Can have both abstract and concrete methods, can have constructors and member variables.
      • Interface: Only abstract methods (prior to Java 8), no member variables, and no constructors. A class can implement multiple interfaces.
  4. What is the purpose of the final keyword in Java?

    • Answer:
      • final variable: Value cannot be changed.
      • final method: Cannot be overridden.
      • final class: Cannot be subclassed.
  5. What is a constructor in Java?

    • Answer: A constructor is a special method used to initialize objects. It has the same name as the class and no return type.
  6. What is method overloading and method overriding?

    • Answer:
      • Method Overloading: Defining methods with the same name but different parameters.
      • Method Overriding: A subclass provides its own implementation of a method already defined in the parent class.
  7. What are the different types of variables in Java?

    • Answer:
      • Local variables: Declared inside methods.
      • Instance variables: Declared in a class, each object has its own copy.
      • Static variables: Declared with the static keyword, shared across all instances of a class.
  8. What is the difference between == and .equals() in Java?

    • Answer:
      • == checks if two references point to the same object in memory.
      • .equals() compares the actual contents of two objects.
  9. What is the purpose of the static keyword?

    • Answer: The static keyword allows members (methods or variables) to belong to the class rather than to instances of the class.
  10. What is the difference between a primitive data type and an object reference in Java?

    • Answer: Primitive data types (e.g., int, char) store actual values, while object references store memory addresses of objects.

Object-Oriented Programming (OOP)

  1. What are the four pillars of Object-Oriented Programming?

    • Answer:
      • Encapsulation: Wrapping data and methods together and restricting access.
      • Abstraction: Hiding implementation details and showing only essential features.
      • Inheritance: Deriving new classes from existing ones to promote code reuse.
      • Polymorphism: Different classes using the same method in different ways.
  2. What is inheritance in Java?

    • Answer: Inheritance allows a subclass to inherit fields and methods from a superclass, promoting code reuse.
  3. What is polymorphism? How is it implemented in Java?

    • Answer: Polymorphism allows objects to be treated as instances of their parent class. It is implemented using method overriding and interfaces.
  4. What is encapsulation and why is it important in Java?

    • Answer: Encapsulation hides internal object details and provides access through getter and setter methods to ensure control over data.
  5. What is abstraction in Java?

    • Answer: Abstraction involves hiding the implementation details and showing only essential features. It is achieved using abstract classes or interfaces.
  6. Explain the concept of "Object Serialization" in Java.

    • Answer: Serialization is the process of converting an object into a byte stream to be saved or transmitted. The object needs to implement the Serializable interface.
  7. What is the difference between this and super in Java?

    • Answer:
      • this refers to the current instance of the class.
      • super refers to the superclass.
  8. What are constructors and what types of constructors are there in Java?

    • Answer: A constructor initializes objects. There are two types:
      • Default constructor (no arguments).
      • Parameterized constructor (with arguments).
  9. What is a singleton class and how is it implemented in Java?

    • Answer: A singleton class ensures only one instance is created. It is implemented by making the constructor private and providing a static method to return the single instance.
  10. What is the difference between composition and inheritance?

    • Answer:
      • Inheritance: A subclass inherits the behavior of the parent class.
      • Composition: An object "has-a" another object (a relationship where one class contains an instance of another class).

Exception Handling

  1. What is the difference between checked and unchecked exceptions in Java?

    • Answer:
      • Checked exceptions must be either caught or declared (e.g., IOException).
      • Unchecked exceptions (runtime exceptions) don't require explicit handling (e.g., NullPointerException).
  2. How do you handle exceptions in Java?

    • Answer: Exceptions are handled using try-catch blocks. The finally block runs whether an exception occurs or not.
  3. What is the purpose of try, catch, and finally blocks?

    • Answer:
      • try: Contains code that may throw exceptions.
      • catch: Catches and handles exceptions.
      • finally: Executes after the try-catch block, whether an exception is thrown or not.
  4. What is a custom exception and how do you create one in Java?

    • Answer: A custom exception is a user-defined class that extends Exception. It can be created by defining a new class that calls super(message) in the constructor.
  5. Explain the concept of "throw" and "throws" in Java.

    • Answer:
      • throw: Used to explicitly throw an exception.
      • throws: Declares exceptions that a method may throw.
  6. What is the difference between Exception and Error in Java?

    • Answer:
      • Exception: Represents conditions that a program can recover from.
      • Error: Represents serious issues that the program cannot recover from (e.g., OutOfMemoryError).

Collections Framework

  1. What is the Java Collections Framework?

    • Answer: The Java Collections Framework is a set of classes and interfaces that implement commonly used data structures like lists, sets, and maps.
  2. What are the differences between a List, Set, and Map?

    • Answer:
      • List: An ordered collection that allows duplicates.
      • Set: An unordered collection that does not allow duplicates.
      • Map: A collection of key-value pairs, with unique keys.
  3. Explain the difference between ArrayList and LinkedList.

    • Answer:
      • ArrayList: Implements a dynamic array, providing fast access but slower insertions/removals.
      • LinkedList: Implements a doubly linked list, providing faster insertions/removals but slower access by index.
  4. What is the purpose of the Iterator interface?

    • Answer: The Iterator interface allows for traversing a collection (e.g., ArrayList, HashSet) and removing elements during iteration.
  5. What is the difference between HashMap and TreeMap in Java?

    • Answer:
      • HashMap: Does not guarantee order of elements.
      • TreeMap: Stores keys in sorted order according to their natural ordering or a comparator.
  6. How does a HashSet work in Java?

    • Answer: A HashSet uses a hash table to store elements, ensuring no duplicates and allowing fast access.
  7. What is the difference between ArrayList and Vector?

    • Answer:
      • ArrayList: Not synchronized and more efficient.
      • Vector: Synchronized, slower due to synchronization overhead.
  8. What is the role of Comparator and Comparable interfaces in Java?

    • Answer:
      • Comparable: Used for natural ordering of objects.
      • Comparator: Used for custom ordering.
  9. What is the purpose of Collections.sort()?

    • Answer: The Collections.sort() method sorts elements in a collection according to their natural ordering or a custom comparator.

Multithreading and Concurrency

  1. What is a thread in Java?

    • Answer: A thread is a lightweight process that allows for concurrent execution of code within a program.
  2. What is the difference between a process and a thread in Java?

    • Answer:
      • Process: An independent program with its own memory space.
      • Thread: A part of a process that shares the same memory space.
  3. What are the various ways to create a thread in Java?

    • Answer:
      • Implement the Runnable interface and pass it to a Thread object.
      • Extend the Thread class and override the run() method.
  4. What is the role of the synchronized keyword in Java?

    • Answer: The synchronized keyword ensures that only one thread can access a method or block at a time, preventing thread interference.
  5. What are deadlock, livelock, and starvation in Java?

    • Answer:
      • Deadlock: Threads are blocked forever because they are waiting on each other.
      • Livelock: Threads are actively trying to avoid deadlock but still can’t proceed.
      • Starvation: Threads are not getting the necessary resources because other threads keep taking precedence.
  6. Explain the concept of ExecutorService in Java.

    • Answer: ExecutorService is an interface for managing and controlling thread execution, providing methods for submitting tasks and shutting down threads.
  7. What is the difference between wait(), notify(), and notifyAll() in Java?

    • Answer:
      • wait(): Causes the current thread to wait until notified.
      • notify(): Wakes up one waiting thread.
      • notifyAll(): Wakes up all waiting threads.
  8. What is the volatile keyword used for in Java?

    • Answer: The volatile keyword ensures that a variable's value is read from and written to main memory, not cached by threads.
  9. What are Callable and Future interfaces used for in Java?

    • Answer:
      • Callable: Represents tasks that can be executed concurrently and can return a result or throw an exception.
      • Future: Represents the result of an asynchronous computation.

Java Memory Management

  1. What is garbage collection in Java?

    • Answer: Garbage collection automatically reclaims memory from objects that are no longer in use, preventing memory leaks.
  2. What is the role of the finalize() method in Java?

    • Answer: finalize() is called by the garbage collector before an object is destroyed to perform cleanup tasks.
  3. What is the difference between stack and heap memory in Java?

    • Answer:
      • Stack: Stores method calls and local variables, with LIFO access.
      • Heap: Stores objects created at runtime and is shared across all threads.
  4. Explain memory leaks and how to avoid them in Java.

    • Answer: Memory leaks occur when objects that are no longer needed are still referenced. Avoid them by nullifying references when they are no longer needed.

Java 8 and Advanced Features

  1. What are Lambda expressions in Java 8?

    • Answer: Lambda expressions enable passing behavior (code) as parameters to methods, simplifying the development of functional-style code.
  2. What are Streams in Java 8, and how do you use them?

    • Answer: Streams in Java 8 provide a way to process sequences of elements in a functional style, allowing operations like filtering, mapping, and reducing.
  3. What is the difference between map() and flatMap() in Java 8 Streams?

  • Answer:
    • map(): Transforms each element in the stream into a new element.
    • flatMap(): Transforms each element into a stream of elements, effectively flattening the structure.
  1. What are functional interfaces in Java 8?
  • Answer: A functional interface is an interface with just one abstract method. It can be used as the target for lambda expressions. Examples include Runnable, Callable, Comparator, etc.
  1. Explain the concept of Optional in Java 8.
  • Answer: Optional is a container object used to represent the absence or presence of a value. It avoids NullPointerException by providing methods to handle empty values safely.
  1. What are method references in Java 8?
  • Answer: Method references are a shorthand notation of a lambda expression to call a method. For example, ClassName::methodName.
  1. What is the default keyword in Java 8 interfaces?
  • Answer: The default keyword allows methods in interfaces to have an implementation. It helps maintain backward compatibility with older versions of interfaces.
  1. What is the static keyword in Java 8 interfaces?
  • Answer: The static keyword allows you to define static methods in interfaces. These methods can be called using the interface name, just like static methods in classes.
  1. What is the difference between forEach() and collect() in Java 8 Streams?
  • Answer:
    • forEach(): Performs an action for each element in the stream (primarily for side-effects).
    • collect(): Collects the elements of the stream into a different form, such as a list, set, or map.
  1. What are the main benefits of using streams in Java 8?
  • Answer: Streams provide a more readable and concise way to process sequences of elements, supporting functional programming paradigms like map/filter/reduce, and enabling parallel processing for better performance.
  1. Explain the concept of Collectors in Java 8.
  • Answer: Collectors is a utility class in Java 8 that provides methods to collect elements from a stream into collections, such as lists, sets, and maps, or to perform reduction operations like summing or averaging.
  1. What is the Comparator interface and how do you use it in Java?
  • Answer: The Comparator interface is used to define custom sorting logic for objects. You can implement it and pass it to methods like Collections.sort() or stream.sorted().

Java Design Patterns

  1. What is the Singleton design pattern in Java?
  • Answer: The Singleton pattern ensures that only one instance of a class is created. It is implemented by making the constructor private and providing a static method to access the single instance.
  1. What is the Factory Method pattern?
  • Answer: The Factory Method pattern provides a way to delegate the instantiation of objects to subclasses, allowing for flexibility in object creation.
  1. What is the Observer design pattern?
  • Answer: The Observer pattern allows an object (the subject) to notify a list of dependent objects (observers) about state changes. It’s commonly used in event handling.
  1. What is the Strategy design pattern?
  • Answer: The Strategy pattern allows a class to change its behavior at runtime by choosing from a family of algorithms (or strategies) encapsulated in separate classes.
  1. What is the Decorator design pattern?
  • Answer: The Decorator pattern allows you to dynamically add functionality to an object by wrapping it in a decorator class, preserving the object’s original interface.
  1. What is the Command design pattern?
  • Answer: The Command pattern encapsulates a request as an object, allowing for parameterization of clients with queues, requests, and log requests.
  1. What is the Proxy design pattern?
  • Answer: The Proxy pattern provides a surrogate or placeholder for another object, controlling access to it. It’s often used for lazy initialization, access control, or logging.
  1. What is the Adapter design pattern?
  • Answer: The Adapter pattern allows two incompatible interfaces to work together. It acts as a bridge between the client and the adapted class.
  1. What is the Composite design pattern?
  • Answer: The Composite pattern allows clients to treat individual objects and compositions of objects uniformly, often used for tree-like structures.
  1. What is the Builder design pattern?
  • Answer: The Builder pattern allows the construction of complex objects by separating the construction process from the actual representation, making the construction process more flexible.

Java Performance and Optimization

  1. What is the difference between a deep copy and a shallow copy in Java?
  • Answer:
    • Shallow copy: Copies the reference to the objects, not the objects themselves.
    • Deep copy: Copies both the object and all the objects referenced by it, recursively.
  1. What is Java's Just-In-Time (JIT) compiler?
  • Answer: The JIT compiler is part of the JVM that compiles bytecode into native machine code at runtime, optimizing performance.
  1. What is the difference between StringBuilder and StringBuffer?
  • Answer:
    • StringBuilder: Not synchronized, making it faster for single-threaded environments.
    • StringBuffer: Synchronized, making it thread-safe but slower.
  1. What is the difference between ArrayList and LinkedList in terms of performance?
  • Answer:
    • ArrayList: Provides fast random access but slower insertions and deletions.
    • LinkedList: Provides slower random access but faster insertions and deletions, especially for large datasets.
  1. What is the volatile keyword used for in multi-threading?
  • Answer: The volatile keyword ensures that a variable's value is always directly read from and written to the main memory, preventing threads from caching the value.
  1. What is the importance of proper exception handling in performance optimization?
  • Answer: Poor exception handling can lead to unnecessary overhead, especially when exceptions are thrown frequently. Proper exception handling avoids performance degradation and ensures better memory management.
  1. What are memory leaks and how do you prevent them in Java?
  • Answer: Memory leaks occur when objects are no longer in use but are still referenced. They can be prevented by nullifying references and ensuring objects are properly garbage collected.
  1. What is the difference between heap and stack memory?
  • Answer:
    • Stack: Stores method calls, local variables, and primitive types. It is thread-specific.
    • Heap: Stores objects created at runtime and shared across threads.
  1. What is the purpose of System.gc() in Java?
  • Answer: System.gc() is a request to the JVM to perform garbage collection. However, it is only a suggestion and may not immediately trigger garbage collection.
  1. What is the importance of the clone() method in Java?
  • Answer: The clone() method creates a duplicate of an object, allowing you to copy objects when needed. It’s typically used for creating deep or shallow copies.

Java I/O and NIO

  1. What is the difference between byte streams and character streams in Java?
  • Answer:
    • Byte streams: Handle raw binary data (e.g., FileInputStream, FileOutputStream).
    • Character streams: Handle character data (e.g., FileReader, FileWriter), performing automatic encoding and decoding.
  1. What is Java NIO?
  • Answer: Java NIO (New I/O) is a set of APIs introduced in Java 1.4 to handle I/O operations more efficiently. It provides capabilities like buffers, channels, and selectors.
  1. What is the difference between FileInputStream and BufferedInputStream?
  • Answer:
    • FileInputStream: Reads bytes from a file.
    • BufferedInputStream: Buffers input to improve performance by reducing the number of reads from the underlying file system.
  1. What is the purpose of RandomAccessFile in Java?
  • Answer: RandomAccessFile allows you to read from and write to a file at arbitrary positions, supporting both input and output operations.
  1. What is the difference between FileReader and BufferedReader?
  • Answer:
    • FileReader: Reads data from a file one character at a time.
    • BufferedReader: Buffers input, allowing reading of lines or larger chunks of text at once, improving performance.
  1. What is serialization in Java?
  • Answer: Serialization is the process of converting an object into a byte stream for storage or transmission. The object needs to implement Serializable interface.
  1. What is Path and Files in Java NIO?
  • Answer:
    • Path: Represents a file or directory path in a more flexible and platform-independent way.
    • Files: Contains utility methods for reading, writing, and manipulating files.
  1. How do you create a file in Java?
  • Answer: Files can be created using File.createNewFile() (for single files) or Files.createFile(Path path) (for NIO files).
  1. What is the difference between read() and readLine() in Java I/O?
  • Answer:
    • read(): Reads a single byte of data.
    • readLine(): Reads an entire line of text.
  1. How do you handle file exceptions in Java?
  • Answer: Handle file exceptions using try-catch blocks, specifically handling IOException for file-related errors.

Java Database Connectivity (JDBC)

  1. What is JDBC in Java?
  • Answer: JDBC (Java Database Connectivity) is an API that allows Java applications to connect and interact with relational databases.
  1. What is the difference between Statement, PreparedStatement, and CallableStatement in JDBC?
  • Answer:
    • Statement: Executes simple SQL queries.
    • PreparedStatement: Executes precompiled SQL queries, offering better performance and security (e.g., prevention of SQL injection).
    • CallableStatement: Executes stored procedures in the database.
  1. What is a connection pool in JDBC?
  • Answer: A connection pool maintains a set of reusable database connections, improving performance by reducing the overhead of establishing new connections repeatedly.
  1. What is a ResultSet in JDBC?
  • Answer: A ResultSet represents the result set of a query and allows you to iterate through the returned rows of a database query.
  1. What is the auto-commit feature in JDBC?
  • Answer: In JDBC, the auto-commit feature is enabled by default, meaning each individual SQL statement is treated as a transaction. It can be disabled for batch processing.
  1. What is DriverManager in JDBC?
  • Answer: DriverManager manages a list of database drivers, establishing database connections via getConnection().
  1. How do you close database connections in JDBC?
  • Answer: Connections are closed using the close() method on the Connection object to release resources.
  1. What are Transactions in JDBC and how are they handled?
  • Answer: Transactions allow multiple operations to be executed as a single unit. They are managed using methods like commit() and rollback() to ensure data integrity.
  1. What is SQL injection, and how can you prevent it in JDBC?
  • Answer: SQL injection is a security vulnerability where malicious SQL code is inserted into queries. It can be prevented using PreparedStatement to avoid embedding user input directly into SQL queries.
  1. What is a batch update in JDBC?
  • Answer: A batch update allows multiple SQL statements to be executed as a batch, improving performance by reducing the number of database round-trips.

These 100 questions cover a wide array of Java topics, including basic concepts, object-oriented programming, advanced features, multithreading, collections, design patterns, performance optimization, and database connectivity.

J2J Institute private limited