Java interview Questions and Answers

What are the Principal Concepts of OOPS?

Object-Oriented Programming (OOP) is based on four principal concepts:

  1. Abstraction: Abstraction refers to the act of representing essential features without including the background details or explanations.
  2. Encapsulation: Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
  3. Polymorphism: Polymorphism is the ability to create a variable, a method, or an object that has more than one form.
  4. Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class.

Differences Between Abstraction and Encapsulation?

Abstraction and encapsulation are complementary concepts:

  • Abstraction focuses on the behavior of an object.
  • Encapsulation focuses on the implementation of an object’s behavior by hiding the internal state of the object and thus can be seen as a strategy used to provide abstraction.

What is Polymorphism in Java? How do Method Overloading and Method Overriding relate to it.

Polymorphism in Java refers to the ability of a single function, interface, or method name to take multiple forms. It allows the same method name to behave differently based on the context or object that invokes it. Polymorphism supports two main concepts:

1. Method Overloading (Compile-time Polymorphism):

  • Occurs when two or more methods in the same class have the same name but different parameter lists (different number, type, or order of arguments).
    It is resolved at compile-time.

  • Example:

    void print(String message) {} void print(String message, int times) {}

2. Method Overriding (Runtime Polymorphism):

  • Happens when a subclass redefines a method from its parent class with the same name, return type, and parameter list.

  • It is resolved at runtime, based on the object type.

  • The overriding method cannot reduce the visibility of the method being overridden.

  • Example:

    class Parent {
    void show() {}
    }
    class Child extends Parent {
    @Override
    void show() {}
    }

Difference Between Method Overloading and Method Overriding

Feature Method Overloading Method Overriding
Definition Same method name, different parameters Same method name and parameters, different class
Resolution Time Compile-time Runtime
Inheritance Required No Yes (requires parent-child relationship)
Class Scope Within the same class Between superclass and subclass
Return Type Can be the same or different Must be the same (or covariant in newer Java versions)
Access Modifier Can vary Cannot reduce access level of the overridden method
Annotation Used Not required Often marked with @Override annotation

What is the Difference Between an Interface and an Abstract Class?

  • Interface: All methods are implicitly abstract. A class may implement multiple interfaces.
  • Abstract Class: May contain both abstract and non-abstract methods. A class can extend only one abstract class.
  • Implementation Requirements: Interfaces require implementing all declared methods, whereas abstract classes may not require implementing all declared methods.
  • Variable Declarations: Variables in interfaces are final by default. Abstract classes can have non-final variables.
  • Access Modifiers: Members of an interface are public by default. Abstract class members can be private, protected, or public.
  • Instantiation: Interfaces cannot be instantiated. Abstract classes can be instantiated if they contain a main method.

What is Autoboxing and Unboxing?

  • Autoboxing: The automatic conversion by the Java compiler between primitive types and their corresponding object wrapper classes.
  • Unboxing: The reverse operation where an object of a wrapper class is converted back to a corresponding primitive type.

What are the Data Types Supported by Java?

Java supports eight primitive data types:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

What Does the “Static” Keyword Mean? Can You Override Private or Static Methods in Java?

  • Static Keyword: Indicates that a member variable or method can be accessed without requiring an instance of the class.
  • Overriding Static Methods: Not possible as static methods are statically bound at compile time.

String

What is String in Java?

In Java, a String is an object that represents a sequence of characters. It is immutable, meaning once created, it cannot be changed.

Why is String immutable in Java?

String is immutable because:

  • Security – especially in class loading and network connections
  • Thread-safety – can be shared across threads without synchronization
  • Caching – JVM uses string pool to reuse string literals

What is the difference between == and equals() when comparing strings?

Comparison==equals()
ChecksReference (memory address)Actual content
Examplestr1 == str2str1.equals(str2)

What is the String Pool?

The String Pool is a special memory region where Java stores string literals. If two strings have the same value, they share the same reference in the pool.

How to create a string object?

// Using string literal (preferred)
String s1 = "Hello";
// Using new keyword (creates a new object in heap)
String s2 = new String("Hello");

What are common methods in the String class?

  • length() – returns the length
  • charAt(index) – returns the character at a position
  • substring(begin, end) – returns a substring
  • toLowerCase(), toUpperCase() – converts case
  • replace(), trim(), split() – modification and parsing
  • equals(), equalsIgnoreCase(), compareTo() – comparisons

How do you convert a String to an int?

String str = "123";
int num = Integer.parseInt(str);

How to reverse a string in Java?

// Using StringBuilder
String original = "OpenAI";
String reversed = new StringBuilder(original).reverse().toString();

What is the difference between StringBuilder and StringBuffer?

FeatureStringBuilderStringBuffer
Thread-safeNoYes
PerformanceFasterSlower
Introduced InJava 5Java 1.0

What are Java 8 String Enhancements?

  • join(): Joins multiple strings with a delimiter
  • chars(): Returns an IntStream of characters
  • Usage with lambda/streams for functional string processing
// Java 8 join
String joined = String.join("-", "2025", "06", "14"); // Output: 2025-06-14
// Java 8 chars
String str = "Java";
str.chars().forEach(c -> System.out.print((char) c));

Exception Handling:

What is an Exception in Java?

An exception is an event that disrupts the normal flow of the program. It is an object thrown at runtime when an abnormal situation occurs.

What is the Exception Hierarchy?

java.lang.Object └── java.lang.Throwable ├── java.lang.Error // serious problems like OutOfMemoryError └── java.lang.Exception // application-level exceptions ├── java.io.IOException ├── java.sql.SQLException └── java.lang.RuntimeException ├── NullPointerException ├── ArithmeticException └── ArrayIndexOutOfBoundsException

Difference Between Checked and Unchecked Exceptions

FeatureChecked ExceptionUnchecked Exception
InheritanceExtends ExceptionExtends RuntimeException
Compile-time CheckYesNo
ExamplesIOException, SQLExceptionNullPointerException, ArithmeticException
Handled usingtry-catch or throwsOptional

Can you catch multiple exceptions in one block?

Yes, from Java 7 onwards, you can use multi-catch:

try { // risky code } catch (IOException | SQLException e) { e.printStackTrace(); }

Rules of Exception Handling in Method Overriding

  • The overriding method must not throw broader checked exceptions than the overridden method.
  • If the parent method doesn’t throw a checked exception, the child cannot throw one.
// Legal class Parent { void show() throws IOException {} } class Child extends Parent { void show() throws FileNotFoundException {} } // Illegal class Child2 extends Parent { void show() throws Exception {} } // Compilation error

Rules of Exception Handling in Method Overloading

Exception type does not impact method overloading. You can throw any exception from any overloaded version.

void process() throws IOException {} void process(int x) throws SQLException {}
Difference Between throw and throws
Keywordthrowthrows
UsageTo explicitly throw an exceptionDeclares exceptions in method signature
LocationInside method bodyAfter method signature
Examplethrow new IOException();void read() throws IOException

What is the finally block and when is it executed?

The finally block always executes after the try and catch blocks — even if there is a return

statement or an exception was not caught.

Can we override a method that throws an exception with one that doesn’t?

Yes, the child class can override the method and declare fewer or no exceptions than the

parent method. It cannot declare broader exceptions.

Java 8 Enhancements in Exception Handling

  • Multi-catch with final or effectively final variables
  • Improved try-with-resources syntax
  • Cleaner exception propagation using lambdas and streams
try (BufferedReader br = Files.newBufferedReader(Paths.get("file.txt"))) { System.out.println(br.readLine()); }

Multithreading:

What is a Thread in Java?

A thread is an independent path of execution. By employing multiple threads, you can speed up CPU-bound tasks.

What is the Difference Between Thread and Process in Java?

  • Thread: A subset of a process; shares the same memory space.
  • Process: Runs on different memory spaces.

How Do You Implement a Thread in Java?

You can implement a thread by either extending the Thread class or implementing the Runnable interface.

When to Use Runnable vs. Thread in Java?

It's better to implement Runnable than extend Thread if you also want to extend another class.

What is the Difference Between Start() and Run() Method of Thread Class?

  • Start(): Creates a new thread and calls the run() method.
  • Run(): If called directly, no new thread is created; the code runs in the current thread.

What is the Difference Between Calling Wait() and Sleep() Method in Java Multi-threading?

  • Wait(): Used for inter-thread communication, releases the lock.
  • Sleep(): Stops the execution of the current thread for a specified time, does not release the lock.

Why Wait, Notify, and NotifyAll are Not Inside Thread Class?

They are in the Object class because Java provides locks at the object level, not at the thread level.

Explain Why Wait, Notify, and NotifyAll are in Object Class?

  1. They are communication mechanisms between two threads.
  2. Locks are on a per-object basis.
  3. Threads wait for locks, not for specific threads to release locks.

What is the Difference Between Runnable and Callable in Java?

  • Runnable: Doesn't return a result or throw checked exceptions.
  • Callable: Returns a result and can throw checked exceptions.

What is the Difference Between CyclicBarrier and CountDownLatch in Java?

  • CountDownLatch: Cannot be reused once the count reaches zero.
  • CyclicBarrier: Can be reused even after the barrier is broken.

What is Java Memory Model?

A set of rules and guidelines that ensure Java programs behave deterministically across multiple architectures. It provides guarantees for visibility and ordering of variable reads and writes between threads.

What is a Volatile Variable in Java?

A special modifier that guarantees visibility of changes to variables across threads.

What is Thread-Safety? Is Vector a Thread-Safe Class?

Thread-safety ensures that code behaves correctly when accessed by multiple threads concurrently. Vector is a thread-safe class because its methods are synchronized.

What is a Race Condition in Java?

A situation where the outcome depends on the sequence or timing of uncontrollable events, often leading to bugs.

How to Stop a Thread in Java?

  • Rely on the thread finishing the execution of its run() method.
  • Use a volatile boolean variable or call interrupt() to stop the thread manually.

What Happens When an Exception Occurs in a Thread?

If not caught, the thread will die. If an UncaughtExceptionHandler is registered, it will handle the exception.

How Do You Share Data Between Two Threads in Java?

By using shared objects or concurrent data structures like BlockingQueue.

What is the Difference Between Notify and NotifyAll in Java?

  • Notify(): Wakes up one waiting thread.
  • NotifyAll(): Wakes up all waiting threads.

What is ThreadLocal Variable in Java?

A variable that is local to a thread, providing each thread with its own independent instance.

What is FutureTask in Java?

A class representing a cancellable asynchronous computation, implementing the Future interface.

What is the Difference Between Interrupted() and IsInterrupted() Method in Java?

  • Interrupted(): Clears the interrupt status.
  • IsInterrupted(): Does not clear the interrupt status.

Why Wait and Notify Methods are Called from Synchronized Block?

To avoid race conditions and because it's mandatory by Java API. It ensures the thread holds the lock before calling these methods.

Why Should You Check the Condition for Waiting in a Loop?

To avoid false alerts and spurious wake-ups. Always call wait() in a loop to recheck the condition.

What is the Difference Between Synchronized and Concurrent Collection in Java?

  • Synchronized Collection: Ensures thread-safety but may cause contention.
  • Concurrent Collection: Provides better scalability by using techniques like lock stripping and partitioning.

By following these principles and guidelines, you can effectively implement and understand object-oriented programming and multithreading in Java.

Collection:

What are the main interfaces in Java Collections Framework?

  • Collection – Root interface
  • List – Ordered collection (e.g., ArrayList, LinkedList)
  • Set – No duplicates (e.g., HashSet)
  • Queue – FIFO structure (e.g., PriorityQueue)
  • Map – Key-value pairs (e.g., HashMap, TreeMap)

What is the difference between ArrayList and LinkedList?

Feature ArrayList LinkedList
Storage Dynamic array Doubly linked list
Access Time Fast (O(1) access) Slow (O(n) traversal)
Insertion/Deletion Slower in middle Faster in middle
Memory Overhead Low High (due to node pointers)

What is the difference between HashMap and Hashtable?

Feature HashMap Hashtable
Thread Safety Not thread-safe Thread-safe
Null Keys Allows one null key Does not allow null keys
Performance Faster Slower

Difference Between HashMap and ConcurrentHashMap

Feature HashMap ConcurrentHashMap
Thread Safety Not thread-safe Thread-safe (designed for concurrent use)
Performance in multi-threaded environment Poor — requires external synchronization High — uses fine-grained locking (bucket-level)
Null Keys/Values Allows one null key and multiple null values Does not allow null keys or null values
Synchronization Manual (e.g., using Collections.synchronizedMap) Internal synchronization (lock striping)
Introduced In JDK 1.2 JDK 1.5 (java.util.concurrent)
Use Case Single-threaded applications Multi-threaded/concurrent applications

Comments