Java Interview Questions & Answers

Prepare for your next Java interview with our curated list of questions, from basic concepts to advanced topics, all explained clearly.

Beginner Level Questions

1. What is Java?

Java is a high-level, object-oriented programming language designed so you can write code once and run it on almost any device. It's like a universal translator for software, making it a powerful language for web development, mobile apps (Android), and large enterprise systems.

2. What are the key features of Java?

Java's key features include its object-oriented nature, platform independence (meaning it can run anywhere with a JVM), built-in security, robustness (it has strong error checking), and support for multithreading which allows it to do many tasks at once efficiently.

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

Think of it like a factory. The **JDK** is the whole factory, containing all the tools you need to build and compile Java programs. The **JRE** is the assembly line where the finished code actually runs. The **JVM** is the specific engine on the assembly line that executes your code line by line, making it work on different operating systems.

4. What are primitive data types in Java?

Primitive data types are the most basic building blocks for information in Java. They are not objects and represent simple values like `int` for whole numbers, `float` and `double` for decimals, `boolean` for true/false values, and `char` for single letters. They are built directly into the language and are stored directly in the memory.

5. What is a variable?

A variable is a container that holds a value, like a labeled box you can put things in. Each variable has a specific data type and a name. Before you can use a variable, you have to declare it and give it a value, for example: int age = 25;

6. What is a class and an object?

A **class** is a blueprint or a template for creating objects, defining what properties they have and what actions they can perform. An **object** is a specific instance of that class. For example, the `Dog` class is a blueprint for all dogs, but a specific dog named "Fido" is an object created from that class.

7. What is the main method in Java?

The `main` method is the starting point of every Java program. The Java Virtual Machine (JVM) looks for this method to begin execution. Its specific signature must be `public static void main(String[] args)` so the JVM can find and run it properly.


public class MyProgram {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
                            

8. What is the difference between `public`, `private`, and `protected`?

These are access modifiers that control who can use a class, method, or variable. **`public`** means anyone can access it. **`private`** means only the code within the same class can access it. **`protected`** allows access from the same class, subclasses, and other classes in the same package.

9. What is a constructor in Java?

A constructor is a special method used to create an object and set its initial values. It has the same name as the class and does not have a return type. You can have multiple constructors in a class as long as their parameters are different, which is known as constructor overloading.


public class Person {
    String name;
    
    // This is the constructor
    public Person(String personName) {
        this.name = personName;
    }
}
                            

10. What is an `if-else` statement?

An `if-else` statement lets your program make decisions. It checks if a condition is true or false. If the condition is true, the code inside the `if` block runs. If it's false, the code in the `else` block runs instead.


int age = 20;
if (age >= 18) {
    System.out.println("You can vote.");
} else {
    System.out.println("You cannot vote yet.");
}
                            

11. What is a loop?

A loop is a control structure that repeats a block of code multiple times. This is useful for performing repetitive tasks, like printing a message 10 times or going through every item in a list. The most common loops are `for`, `while`, and `do-while` loops.


for (int i = 0; i < 5; i++) {
    System.out.println("This is iteration " + i);
}
                            

12. What is an array?

An array is a data structure used to store a fixed-size collection of elements of the same data type. Think of it as a row of containers where each container has a number starting from 0. You can access each element using its number (index).


String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println(fruits[1]); // Output: Banana
                            

13. What is the difference between `==` and `.equals()`?

The `==` operator compares the memory addresses of two objects to see if they are the exact same object. The `.equals()` method compares the actual content or value of two objects. For primitive types, you can use `==` but for objects (like Strings), you should always use `.equals()` to check if their content is the same.


String s1 = new String("hello");
String s2 = new String("hello");
String s3 = s1;

System.out.println(s1 == s2);      // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
System.out.println(s1 == s3);      // true (same object reference)
                            

14. What is a method in Java?

A method is a block of code that performs a specific action. You define methods inside a class, and they can be called to run their code when needed. This helps keep your code organized and reusable. For example, a `Car` class might have a `startEngine()` method.


public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
                            

15. What is a String?

A `String` is a class in Java that represents a sequence of characters, like text. It's a special type of object and is **immutable**, which means once you create a String, its value cannot be changed. Any operation that seems to change a string actually creates a new String object.


String greeting = "Hello";
greeting = greeting + " World"; // This creates a NEW String object
System.out.println(greeting);    // Output: Hello World
                            

16. What is the difference between `break` and `continue`?

Both are used inside loops. The `break` statement stops the loop completely and exits it. The `continue` statement skips the current iteration of the loop and moves on to the next one, but the loop continues to run.


// Example of break
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Loop stops when i is 5
    }
    System.out.println(i); // Prints 0, 1, 2, 3, 4
}

// Example of continue
for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // Skips printing 2
    }
    System.out.println(i); // Prints 0, 1, 3, 4
}
                            

17. What is method overloading?

Method overloading is when you have multiple methods in the same class with the same name, but with different parameters (number, type, or order). It lets you perform similar operations in different ways using the same method name, making your code more readable and organized.


public class Math {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(double a, double b) {
        return a + b;
    }
}
                            

18. What is a package?

A package is a way to group related classes and interfaces into a single unit. It's like a folder in your computer's file system, used to organize files and avoid naming conflicts. For example, Java's built-in classes like `String` are in the `java.lang` package.


package com.mycompany.app;

import java.util.ArrayList;

public class MyClass {
    // My class code here
}
                            

19. What is an interface?

An interface is a blueprint that a class must follow. It contains a set of abstract methods (methods without a body) that any class implementing it must provide code for. It's used to achieve a form of multiple inheritance and to define a common contract for different classes, ensuring they all have a certain set of behaviors.


public interface Vehicle {
    void start(); // A method without a body
    void stop();
}

public class Car implements Vehicle {
    @Override
    public void start() {
        // implementation for a car
    }
    
    @Override
    public void stop() {
        // implementation for a car
    }
}
                            

20. What is a static keyword?

The `static` keyword means that a variable or method belongs to the class itself, not to any specific object of that class. You can access static members directly using the class name, without needing to create an object first. A common example is the `main` method, which is static so the JVM can run it without creating an object of the class.


public class Counter {
    static int count = 0; // belongs to the class
    
    public void increment() {
        count++;
    }
}

// You can access 'count' like this:
// int currentCount = Counter.count;
                            

21. What is an exception?

An exception is an event that disrupts the normal flow of a program. It's a problem that occurs during execution, like trying to divide by zero or accessing a file that doesn't exist. Java provides an exception handling mechanism (`try-catch` blocks) to gracefully manage these errors and prevent the program from crashing.

22. What is a `try-catch` block?

A `try-catch` block is a way to handle exceptions. You put the code that might cause an error inside the `try` block. If an exception occurs, the program immediately jumps to the `catch` block, where you can write code to handle the error and prevent the program from stopping unexpectedly.


try {
    int result = 10 / 0; // This will cause an exception
} catch (ArithmeticException e) {
    System.out.println("You can't divide by zero!");
}
                            

23. What is garbage collection?

Garbage collection is an automatic memory management process in Java. The garbage collector automatically finds and deletes objects that are no longer being used by the program. This frees up memory, so you don't have to worry about manually managing memory yourself. It's a key feature that makes Java a safe and robust language.

24. What is the `final` keyword?

The `final` keyword is used to make something unchangeable. When you apply it to a variable, the variable becomes a constant that cannot be reassigned. When you apply it to a method, the method cannot be overridden by a subclass. When used with a class, it means the class cannot be inherited from.


final int MAX_VALUE = 100; // a constant variable
// MAX_VALUE = 200; would cause a compile-time error
                            

25. What is method overriding?

Method overriding occurs when a subclass provides its own specific implementation for a method that is already defined in its superclass. This allows you to create a specific behavior for a method in the subclass without changing the original method in the parent class. You use the `@Override` annotation to indicate this.


class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound.");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The cat meows.");
    }
}
                            

26. What is a static block?

A static block is a special block of code that is executed only once when the class is loaded into memory by the Java Class Loader. It's typically used to initialize static variables or to perform a one-time setup that is needed for the entire class, regardless of how many objects are created.


class MyClass {
    static {
        System.out.println("Static block is executed.");
    }
}
                            

27. What is polymorphism?

Polymorphism means "many forms." In Java, it allows objects of different classes to be treated as objects of a common superclass. This means a single variable can hold different types of objects, and a single method can have different implementations depending on the object it is called on.


Animal myAnimal = new Dog(); // myAnimal is an Animal, but behaves like a Dog
myAnimal.makeSound(); // The dog meows, because the Dog class overrode the method.
                            

28. What is method overriding and overloading?

Overriding and overloading are both forms of polymorphism, but they are different. **Overloading** is when multiple methods have the same name but different parameters within the same class. **Overriding** is when a subclass re-implements a method that is already present in its superclass.


// Overloading example (same method name, different parameters)
public class Calculator {
    int add(int a, int b) { ... }
    double add(double a, double b) { ... }
}

// Overriding example (subclass re-implements a method from its parent)
public class Animal {
    void speak() { ... }
}
public class Cat extends Animal {
    void speak() { ... } // overrides speak() from Animal
}
                            

29. What is a wrapper class?

A wrapper class is a class whose object wraps or contains a primitive data type. It provides a way to use primitive types as objects. For every primitive data type in Java, there is a corresponding wrapper class, such as `Integer` for `int`, `Double` for `double`, and `Character` for `char`. This is useful in the Java Collections Framework, which only works with objects.


int myInt = 5;
Integer myInteger = new Integer(myInt); // Wrapping the primitive 'int'
                            

30. What is a super keyword?

The `super` keyword is used inside a subclass to refer to members of its immediate parent class. You can use `super` to call a parent class's constructor, method, or access its fields. This is helpful when a subclass has a method with the same name as the parent, but you still want to use the parent's version.


class Animal {
    public Animal() {
        System.out.println("Animal created");
    }
}
class Dog extends Animal {
    public Dog() {
        super(); // Calls the parent's constructor
        System.out.println("Dog created");
    }
}
                            

Intermediate Level Questions

31. What is an abstract class?

An abstract class is a class that cannot be instantiated directly. It's meant to be a superclass that provides a common base for other classes. It can contain both abstract methods (methods with no implementation) and concrete methods. Subclasses must provide an implementation for all abstract methods.


public abstract class Shape {
    public abstract double getArea(); // Abstract method
    public void printInfo() {
        System.out.println("This is a shape.");
    }
}
                            

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

An **abstract class** is a class that can have both abstract and non-abstract methods, can have constructors, and can have any access modifier. An **interface** is a blueprint that can only contain abstract methods and static final variables (in older Java versions), but with Java 8+, it can also have default and static methods. A class can extend only one abstract class but can implement multiple interfaces.

33. What is encapsulation?

Encapsulation is the concept of bundling data (fields) and methods that operate on that data into a single unit (a class). It also restricts direct access to some of an object's components, which is typically done by using `private` access modifiers and providing `public` methods (`getters` and `setters`) to control how the data is accessed and modified. This protects the data from accidental corruption.


public class Person {
    private String name; // Private data field
    
    public String getName() { // Public getter method
        return name;
    }
    
    public void setName(String newName) { // Public setter method
        this.name = newName;
    }
}
                            

34. What is inheritance?

Inheritance is an object-oriented concept where a new class (`child` or `subclass`) is created from an existing class (`parent` or `superclass`). The child class inherits the fields and methods of the parent class, allowing for code reuse and creating an "is-a" relationship (e.g., a `Dog` is an `Animal`).


class Animal {
    void eat() { ... }
}

class Dog extends Animal { // Dog inherits from Animal
    void bark() { ... }
}
                            

35. What is the final keyword?

The `final` keyword is used to make something unchangeable. When applied to a variable, it makes it a constant. When applied to a method, it prevents it from being overridden by a subclass. When applied to a class, it prevents the class from being inherited. It's often used for security and performance optimizations.


final int DAYS_IN_WEEK = 7;
// DAYS_IN_WEEK = 8; // This would cause a compile-time error
                            

36. What is a checked exception vs. an unchecked exception?

A **checked exception** is an exception that the compiler forces you to handle. These are typically problems that can be anticipated and recovered from, like `IOException` or `SQLException`. An **unchecked exception** is an exception that the compiler does not force you to handle. These usually indicate programming errors, like `NullPointerException` or `ArrayIndexOutOfBoundsException`.

37. What is a singleton class?

A singleton class is a class that can only have one object (an instance) at a time. This is useful when you need to ensure that there is only one instance of a class throughout the application's lifecycle, for example, a database connection pool or a configuration manager.


public class Singleton {
    private static Singleton instance;
    private Singleton() { }
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
                            

38. What is a static method?

A static method belongs to the class itself, not to any specific object. You can call it without creating an object of the class. A static method can only access other static members of the class and cannot use keywords like `this` or `super`.


public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}
int sum = MathUtil.add(5, 3); // Calling without an object
                            

39. What is the difference between `ArrayList` and `LinkedList`?

Both are implementations of the `List` interface. An **`ArrayList`** uses a dynamic array to store elements. It provides fast access (retrieving elements by index) but is slow for insertions and deletions in the middle. A **`LinkedList`** stores elements as nodes, where each node has a reference to the next node. It is fast for insertions and deletions but slow for random access.

40. What is a hash map?

A `HashMap` is a data structure that stores key-value pairs. It provides fast lookup, insertion, and deletion of elements by using a hash table. The key must be unique, and the values can be duplicated. Keys and values can be of any object type.


import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 88);
System.out.println(scores.get("Alice")); // Output: 95
                            

41. How do you create an immutable class?

To create an immutable class, follow these steps: 1) Make the class `final` so it cannot be inherited. 2) Make all fields `private` and `final`. 3) Don't provide setter methods. 4) If a field is a mutable object, make sure to clone it in the constructor and getter methods to prevent external modification. The `String` class is a perfect example of an immutable class.

42. What is a thread?

A thread is a single sequence of execution within a program. It is the smallest unit of processing. Multithreading is a concept where a program can have multiple threads running at the same time, which allows for parallel processing and can make an application more responsive. You can create a thread by extending the `Thread` class or implementing the `Runnable` interface.

43. What is the difference between `Error` and `Exception`?

An **`Error`** is a serious problem that is typically unrecoverable, like a memory leak (`OutOfMemoryError`) or a stack overflow (`StackOverflowError`). You are generally not expected to handle errors. An **`Exception`** is a problem that can often be caught and handled, allowing the program to continue running. Exceptions are further divided into checked and unchecked exceptions.

44. What is a `finally` block?

A `finally` block is used with `try-catch` blocks. The code inside the `finally` block is guaranteed to execute, whether an exception is thrown or not. It's most commonly used for cleanup tasks like closing files, database connections, or network sockets to prevent resource leaks.


try {
    // some code
} catch (Exception e) {
    // handle exception
} finally {
    System.out.println("This code always runs.");
}
                            

45. What is the difference between `abstract` and `final`?

The `abstract` keyword is used for classes and methods that are incomplete. An abstract class cannot be instantiated, and an abstract method must be implemented by a subclass. The `final` keyword is used to prevent modification or extension. A final class cannot be extended, a final method cannot be overridden, and a final variable cannot be reassigned.

46. What is a functional interface?

A functional interface is an interface that contains exactly one abstract method. It's a key part of Java's lambda expressions and is often used to pass a function as an argument to a method. The `@FunctionalInterface` annotation is used to tell the compiler that the interface is intended to be a functional interface.


@FunctionalInterface
interface MyFunction {
    int apply(int x, int y);
}
                            

47. What is a lambda expression?

A lambda expression is a short way to represent an anonymous function (a function without a name). It provides a clean and concise way to write code for functional interfaces. Lambda expressions are a key feature of Java 8 and are used to make code more readable and expressive.


// Lambda expression to add two numbers
MyFunction add = (x, y) -> x + y;
int result = add.apply(5, 3); // result is 8
                            

48. What is a stream in Java?

A stream is a sequence of elements that can be processed in a functional way, such as filtering, mapping, and reducing. They were introduced in Java 8 and provide a powerful way to handle collections of data without using traditional loops. Streams don't modify the original data source and are executed lazily, which can be more efficient.


import java.util.Arrays;
import java.util.List;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
       .filter(n -> n % 2 == 0) // filters for even numbers
       .forEach(System.out::println); // prints 2, 4
                            

49. What is the difference between `throw` and `throws`?

`throw` is a statement used to manually throw an exception inside a method, for example, `throw new IllegalArgumentException("Invalid input");`. `throws` is a keyword used in a method signature to declare that a method might throw one or more exceptions. This tells the calling code to handle the exception.


// Using throws
public void readFile() throws FileNotFoundException {
    // code that might throw FileNotFoundException
}

// Using throw
public void checkAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative.");
    }
}
                            

50. What is a Collection Framework?

The Java Collections Framework is a set of interfaces and classes that provides a way to store and manipulate groups of objects. It includes interfaces like `List`, `Set`, and `Map`, and concrete classes like `ArrayList`, `HashSet`, and `HashMap`. It offers reusable data structures that are fast and efficient for various programming tasks.

Advanced Level Questions

51. What is the difference between `fail-fast` and `fail-safe` iterators?

**Fail-fast** iterators (e.g., `ArrayList`, `HashMap`) immediately throw a `ConcurrentModificationException` if a collection is modified while it is being iterated over by another thread. **Fail-safe** iterators (e.g., `ConcurrentHashMap`, `CopyOnWriteArrayList`) do not throw an exception. They work on a cloned copy of the collection, so modifications to the original collection are not reflected in the iterator. This makes them safer for multithreaded environments.

52. What is the `volatile` keyword?

The `volatile` keyword is used for multithreading. It guarantees that any changes made to a variable by one thread will be immediately visible to all other threads. It prevents threads from caching the value of the variable locally, ensuring that they always read the most up-to-date value from main memory. It's crucial for thread-safe programming where multiple threads need to access and modify a shared variable.


public class SharedVariable {
    private volatile boolean isRunning = false;
    
    public void start() {
        isRunning = true;
    }
    
    public boolean isRunning() {
        return isRunning;
    }
}
                            

53. What is a marker interface?

A marker interface is an interface that has no methods or constants. It is used to "mark" a class with a specific capability or property, which is then handled by the Java compiler or JVM at runtime. Examples include `Serializable`, `Cloneable`, and `RandomAccess`. For instance, a class implementing `Serializable` tells the JVM that its objects can be serialized (converted to a byte stream).

54. What is `transient` keyword?

The `transient` keyword is used to mark a field in a class as not to be serialized. When an object is written to a file or stream, the value of transient variables is ignored. This is useful for sensitive data (like passwords) or data that can be re-calculated and doesn't need to be saved with the object's state.


import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private transient String password; // This will not be serialized
}
                            

55. What is the difference between `sleep()` and `wait()`?

The `sleep()` method is part of the `Thread` class. It pauses the current thread for a specified amount of time, but the thread still holds onto any locks it has. The `wait()` method is part of the `Object` class. It tells the calling thread to give up its lock on an object and go to a waiting state until another thread calls the `notify()` or `notifyAll()` method on the same object. `wait()` must be called from a synchronized block.

56. What is a thread pool?

A thread pool is a group of pre-created, reusable threads. Instead of creating a new thread for every task, tasks are submitted to the thread pool, which then uses an available thread to execute the task. This saves resources and overhead of creating and destroying threads repeatedly, leading to better performance and resource management, especially in applications with many short-lived tasks.

57. What is the `String Pool`?

The String Pool is a special storage area in the heap memory where unique string literals are stored. When you create a String using a literal (e.g., `String s = "hello";`), the JVM first checks the pool. If "hello" already exists, it returns a reference to it. If not, it creates a new String in the pool. This is an optimization to save memory. Strings created with `new String("hello")` are not placed in the pool by default.

58. What is a strong, soft, weak, and phantom reference?

These are different types of object references in Java that affect how the garbage collector handles an object. **Strong references** are the most common and prevent an object from being garbage collected. **Soft references** allow an object to be garbage collected if the JVM needs memory. **Weak references** are collected the next time the garbage collector runs. **Phantom references** are for post-mortem cleanup, notifying you after an object has been finalized and is about to be collected.

59. What is a race condition?

A race condition is a bug that occurs in a multithreaded application when multiple threads try to access and modify shared data simultaneously, and the final outcome depends on the unpredictable timing of their execution. This can lead to inconsistent results and data corruption. Race conditions are typically solved using synchronization mechanisms like locks (`synchronized` keyword).

60. What is a deadlock?

A deadlock is a situation in a multithreaded environment where two or more threads are blocked forever, waiting for each other to release a resource. For example, Thread A holds a lock on resource 1 and waits for resource 2, while Thread B holds a lock on resource 2 and waits for resource 1. Both threads are stuck and cannot proceed.

61. How do you prevent deadlocks?

Deadlocks can be prevented by breaking one of the four conditions necessary for a deadlock to occur: mutual exclusion, hold and wait, no preemption, and circular wait. The most common strategies are to prevent the "hold and wait" condition by having threads acquire all needed locks at once, or to break the "circular wait" condition by imposing a strict ordering on lock acquisition.

62. What are the benefits of using a thread pool?

Thread pools offer several benefits: they reduce the overhead of thread creation and destruction, provide a way to manage the number of threads running simultaneously, and improve application responsiveness by allowing tasks to be processed immediately without waiting for a new thread to be created.

63. What is the difference between `HashSet` and `TreeSet`?

Both implement the `Set` interface. A **`HashSet`** is an unordered collection that uses a hash table for storage. It offers constant time performance for basic operations (add, remove, contains) but provides no guarantee on the order of elements. A **`TreeSet`** is a sorted collection that stores elements in a tree data structure. It guarantees that elements are stored in ascending order, but performance is slightly slower (logarithmic time) than `HashSet`.

64. What is a Java annotation?

An annotation is a form of metadata that provides information about a program without affecting its execution. Annotations are used by the compiler, the JVM, or other tools to process a class or method. Common annotations include `@Override` to indicate a method is overriding a superclass method, and `@Deprecated` to mark a method as outdated.


@Override
public void someMethod() {
    // method implementation
}
                            

65. What is the difference between `throw` and `throws`?

`throw` is a statement used within a method to explicitly throw an exception object. `throws` is a keyword used in a method's signature to declare that the method may throw a certain type of exception. `throws` alerts the calling code to be prepared to handle that exception, while `throw` actually performs the action of raising the exception.

66. What is a lambda expression?

A lambda expression is a new feature in Java 8 that provides a short way to write anonymous methods. It is used to implement a functional interface. Lambda expressions make your code more concise, especially for handling collections with streams and for event handling.


// Lambda to print each item in a list
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));
                            

67. What is a static block?

A static block is a code block that is executed only once when a class is loaded into memory. It is typically used for initializing static variables or for performing one-time setup tasks that are required for the entire class. It's guaranteed to run before any object of the class is created and before the `main` method is executed.


class MyClass {
    static {
        System.out.println("Static block executed.");
    }
}
                            

68. What is the difference between `final`, `finally`, and `finalize`?

**`final`** is a keyword used for non-access modifiers. It can be applied to a variable (making it a constant), a method (preventing it from being overridden), or a class (preventing it from being inherited). **`finally`** is a block of code used with a `try-catch` block that is always executed, whether an exception occurs or not. **`finalize`** is a method called by the garbage collector on an object when it's determined that there are no more references to the object. It's not reliable and its use is discouraged in modern Java.

69. What is a `Thread` and `Runnable`?

`Thread` and `Runnable` are two ways to implement multithreading. You can create a thread by extending the `Thread` class or by implementing the `Runnable` interface. Implementing `Runnable` is generally preferred because Java doesn't support multiple inheritance, so extending `Thread` prevents you from extending any other class. Using `Runnable` also decouples the task from the thread itself, making it more flexible.

70. What is a `synchronized` block?

A `synchronized` block is used to ensure that only one thread can execute a certain section of code at a time. This is used to prevent race conditions when multiple threads are accessing shared resources. When a thread enters a synchronized block, it acquires a lock on the object, and other threads are blocked until the first thread exits the block and releases the lock.


public void synchronizedMethod() {
    synchronized(this) {
        // Only one thread can execute this code at a time
    }
}
                            

71. What is the difference between `HashMap` and `Hashtable`?

Both store key-value pairs but have key differences. A `HashMap` is not synchronized and is not thread-safe. It allows one null key and multiple null values. A `Hashtable` is synchronized and is thread-safe, but it is slower because of the synchronization overhead. It does not allow null keys or null values. `Hashtable` is considered a legacy class, and `HashMap` is generally preferred in single-threaded environments.

72. What is an inner class?

An inner class is a class defined inside another class. They are used to logically group classes that are only used in one place, increase encapsulation, and make the code more readable. Inner classes have access to the members of the outer class, even private ones. There are several types of inner classes: member, local, anonymous, and static nested classes.

73. What is the difference between `String` and `StringBuilder`?

The main difference is mutability. `String` is immutable, meaning its value cannot be changed after creation. Any modification creates a new String object. `StringBuilder` is mutable, so its value can be changed without creating a new object. `StringBuilder` is more efficient for operations that involve frequent modification of strings, such as building a large string from multiple smaller ones in a loop.

74. What is a generic in Java?

Generics are a feature that allows you to write classes, interfaces, and methods that work with different types of objects while still providing type safety. This lets you catch type errors at compile time instead of runtime. For example, `ArrayList` is a generic class that ensures you can only add `String` objects to the list.


// A generic class
public class Box {
    private T t;
    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Box integerBox = new Box();
                            

75. What is the `Comparable` and `Comparator` interface?

Both are used to sort objects in Java. The **`Comparable`** interface is used to define the natural sorting order of an object. A class that implements `Comparable` defines how its own objects should be compared. The **`Comparator`** interface defines a separate, custom sorting order. You can pass a `Comparator` to a sorting method (like `Collections.sort()`) to sort objects in different ways without changing the original class.

76. What is a ClassLoader?

A ClassLoader is a part of the Java Runtime Environment (JRE) that dynamically loads Java classes into the JVM. It is responsible for locating, loading, and linking the `.class` files. The JVM has a bootstrap class loader for core libraries and an extension class loader for other parts. Understanding ClassLoaders is important for advanced topics like reflection and dynamic proxies.

77. What is reflection?

Reflection is a powerful feature in Java that allows an executing Java program to inspect and manipulate its own structure (classes, methods, fields) at runtime. You can use reflection to create objects, call methods, and access fields of a class, even if they are private. It is a key technology behind many frameworks like Spring and Hibernate, but it should be used carefully as it can have performance overhead and breaks encapsulation.

78. What is the difference between `throw` and `throws`?

`throw` is a statement used within a method to explicitly throw an exception object. `throws` is a keyword used in a method's signature to declare that the method may throw a certain type of exception. `throws` alerts the calling code to be prepared to handle that exception, while `throw` actually performs the action of raising the exception.


// Using throws
public void readFile() throws FileNotFoundException {
    // code that might throw FileNotFoundException
}

// Using throw
public void checkAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative.");
    }
}
                            

79. What is a lambda expression?

A lambda expression is a new feature in Java 8 that provides a short way to write anonymous methods. It is used to implement a functional interface. Lambda expressions make your code more concise, especially for handling collections with streams and for event handling.


// Lambda to print each item in a list
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));
                            

80. What is the `transient` keyword?

The `transient` keyword is used to mark a field in a class as not to be serialized. When an object is written to a file or stream, the value of transient variables is ignored. This is useful for sensitive data (like passwords) or data that can be re-calculated and doesn't need to be saved with the object's state.


import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private transient String password; // This will not be serialized
}
                            

81. What is the difference between `final`, `finally`, and `finalize`?

**`final`** is a keyword used for non-access modifiers. It can be applied to a variable (making it a constant), a method (preventing it from being overridden), or a class (preventing it from being inherited). **`finally`** is a block of code used with a `try-catch` block that is always executed, whether an exception occurs or not. **`finalize`** is a method called by the garbage collector on an object when it's determined that there are no more references to the object. It's not reliable and its use is discouraged in modern Java.

82. What is a thread pool?

A thread pool is a group of pre-created, reusable threads. Instead of creating a new thread for every task, tasks are submitted to the thread pool, which then uses an available thread to execute the task. This saves resources and overhead of creating and destroying threads repeatedly, leading to better performance and resource management, especially in applications with many short-lived tasks.

83. What is the difference between `HashSet` and `TreeSet`?

Both implement the `Set` interface. A **`HashSet`** is an unordered collection that uses a hash table for storage. It offers constant time performance for basic operations (add, remove, contains) but provides no guarantee on the order of elements. A **`TreeSet`** is a sorted collection that stores elements in a tree data structure. It guarantees that elements are stored in ascending order, but performance is slightly slower (logarithmic time) than `HashSet`.

84. What is a Java annotation?

An annotation is a form of metadata that provides information about a program without affecting its execution. Annotations are used by the compiler, the JVM, or other tools to process a class or method. Common annotations include `@Override` to indicate a method is overriding a superclass method, and `@Deprecated` to mark a method as outdated.


@Override
public void someMethod() {
    // method implementation
}
                            

85. What is a lambda expression?

A lambda expression is a new feature in Java 8 that provides a short way to write anonymous methods. It is used to implement a functional interface. Lambda expressions make your code more concise, especially for handling collections with streams and for event handling.


// Lambda to print each item in a list
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));
                            

86. What is a static block?

A static block is a code block that is executed only once when a class is loaded into memory. It is typically used for initializing static variables or for performing one-time setup tasks that are required for the entire class. It's guaranteed to run before any object of the class is created and before the `main` method is executed.


class MyClass {
    static {
        System.out.println("Static block executed.");
    }
}
                            

87. What is the difference between `synchronized` and `ReentrantLock`?

`synchronized` is a keyword that provides a built-in locking mechanism, but it has limited flexibility. A `ReentrantLock` is a class that implements the `Lock` interface, providing more advanced features than `synchronized`. With `ReentrantLock`, you have more control, such as being able to try to acquire a lock without waiting, check if a lock is held, and more. It offers more flexibility and is often preferred for complex locking scenarios.

88. What is the `ConcurrentHashMap`?

The `ConcurrentHashMap` is a thread-safe and scalable implementation of the `Map` interface. Unlike `Hashtable`, which locks the entire map, `ConcurrentHashMap` uses a fine-grained locking mechanism that only locks parts of the map. This allows for higher concurrency and better performance in multithreaded environments.

89. What is a `volatile` keyword?

The `volatile` keyword guarantees that a variable's value will be read from and written to main memory, preventing threads from using local cached copies. This ensures that changes made by one thread are immediately visible to all other threads. It is an important tool for ensuring thread safety, especially for status flags or shared variables that are written to by one thread and read by others.


public class SharedVariable {
    private volatile boolean isRunning = false;
    
    public void start() {
        isRunning = true;
    }
}
                            

90. What is a `Future` and `Callable`?

The `Callable` interface is similar to `Runnable`, but it can return a value and throw a checked exception. A `Future` represents the result of an asynchronous computation. It provides methods to check if the computation is complete, wait for its completion, and retrieve the result. This is part of the `java.util.concurrent` package for advanced multithreading tasks.

91. What is the `JVM Heap`?

The JVM Heap is the runtime data area from which memory for all class instances and arrays is allocated. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. It is divided into different sections: Eden, Survivor 0, Survivor 1, and the Tenured (Old) Generation. This is where garbage collection happens.

92. What are the different types of garbage collectors?

The JVM provides several different garbage collectors, each with its own advantages. The most common ones include:

  • **Serial GC:** Simple, for single-core machines.
  • **Parallel GC:** The default for server environments, uses multiple threads for garbage collection.
  • **CMS (Concurrent Mark Sweep) GC:** A low-pause collector.
  • **G1 (Garbage-First) GC:** The modern, high-performance collector designed for multicore machines with large heaps.

93. What is the difference between `try-with-resources` and a normal `try-finally` block?

The `try-with-resources` statement (introduced in Java 7) is a more modern and clean way to handle resources that need to be closed, such as files or database connections. It automatically closes the resources when the `try` block is exited. This is much safer than a `try-finally` block, where a forgotten `close()` call could lead to resource leaks.


try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    // Read from the file
} catch (IOException e) {
    // Handle exception
} // 'br' is automatically closed here
                            

94. What is a `ThreadLocal`?

A `ThreadLocal` is a class that provides thread-local variables. This means that each thread that accesses a `ThreadLocal` variable gets its own private, independently initialized copy of the variable. This is useful for avoiding race conditions and passing data to a group of methods without explicit method arguments.


public static ThreadLocal<String> threadName = ThreadLocal.withInitial(() -> "Default");
                            

95. What is the difference between `sleep()` and `yield()`?

`sleep()` causes the currently executing thread to pause for a specified time, during which it does not consume any CPU time. When it wakes up, it re-enters the runnable state. `yield()` is a hint to the thread scheduler that the current thread is willing to give up its CPU time to other threads of the same priority. It doesn't guarantee that the thread will be swapped out, and it will immediately re-enter the runnable state.

96. What is a `ConcurrentHashMap`?

The `ConcurrentHashMap` is a thread-safe and scalable implementation of the `Map` interface. Unlike `Hashtable`, which locks the entire map, `ConcurrentHashMap` uses a fine-grained locking mechanism that only locks parts of the map. This allows for higher concurrency and better performance in multithreaded environments.

97. What is a `lambda expression`?

A lambda expression is a new feature in Java 8 that provides a short way to write anonymous methods. It is used to implement a functional interface. Lambda expressions make your code more concise, especially for handling collections with streams and for event handling.


// Lambda to print each item in a list
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));
                            

98. What are `serializable` and `transient`?

The `Serializable` marker interface indicates that an object can be converted into a byte stream (serialized). This is useful for storing objects in files or sending them over a network. The `transient` keyword is used on a field to tell the JVM that this field should not be serialized when the object is written out. It's often used for data that is temporary or sensitive, like a password.

99. What are the principles of SOLID?

SOLID is a set of five design principles for writing clean, maintainable, and scalable code. The principles are:

  • **S**ingle-responsibility Principle: A class should have only one reason to change.
  • **O**pen-closed Principle: Classes should be open for extension but closed for modification.
  • **L**iskov Substitution Principle: Objects of a superclass should be replaceable with objects of its subclasses without affecting the program's correctness.
  • **I**nterface Segregation Principle: Clients should not be forced to depend on interfaces they do not use.
  • **D**ependency Inversion Principle: High-level modules should not depend on low-level modules; both should depend on abstractions.

100. What is a `stream` in Java?

A stream is a sequence of elements that can be processed in a functional way, such as filtering, mapping, and reducing. They were introduced in Java 8 and provide a powerful way to handle collections of data without using traditional loops. Streams don't modify the original data source and are executed lazily, which can be more efficient.


import java.util.Arrays;
import java.util.List;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
       .filter(n -> n % 2 == 0) // filters for even numbers
       .forEach(System.out::println); // prints 2, 4
                            

101. What is the difference between `Checked` and `Unchecked` exceptions?

A **Checked Exception** is an exception that the compiler forces you to handle using a `try-catch` block or by declaring it with a `throws` clause. These are usually recoverable and are often caused by external factors, like a file not being found. An **Unchecked Exception** is an exception that you are not forced to handle. These are typically runtime errors that indicate a bug in the code, such as a `NullPointerException` or `ArrayIndexOutOfBoundsException`.

Ready for the Python Challenge?

Test your knowledge with our Python Interview Questions & Answers. Click below to dive in!

Stay Updated

Get coding tips and resource updates. No spam.

We respect your privacy. Unsubscribe at any time.