top of page

The Ultimate Java Interview Questions Guide 2025 : Part-2

Java 8+ Features

Q33: What are lambda expressions?

Lambda expressions provide a concise way to represent functional interfaces:

// Before Java 8
Runnable r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running");
    }
};

// With lambda
Runnable r2 = () -> System.out.println("Running");

// List sorting before Java 8
Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.compareTo(b);
    }
});

// With lambda
Collections.sort(list, (a, b) -> a.compareTo(b));
// Or method reference
Collections.sort(list, String::compareTo);

Q34: What are functional interfaces?

Interfaces with exactly one abstract method:

@FunctionalInterface
public interface Calculator {
    int calculate(int a, int b);
    
    // Can have default and static methods
    default void print() {
        System.out.println("Calculator");
    }
}

// Built-in functional interfaces
Function<StringInteger> stringLength = s -> s.length();
Predicate<Integer> isEven = n -> n % 2 == 0;
Consumer<String> printer = System.out::println;
Supplier<String> stringSupplier = () -> "Hello World";

Q35: What is Stream API?

Stream API provides functional-style operations on collections:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Filter even numbers, square them, and collect
List<Integer> result = numbers.stream()
    .filter(n -> n % 2 == 0)        // Filter even numbers
    .map(n -> n * n)                // Square each number
    .collect(Collectors.toList());  // Collect to list

// Find first element greater than 5
Optional<Integer> found = numbers.stream()
    .filter(n -> n > 5)
    .findFirst();

// Group by even/odd
Map<BooleanList<Integer>> grouped = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

Q36: What is Optional class?

Optional helps avoid NullPointerException:

// Without Optional
public String getName(Person person) {
    if (person != null && person.getName() != null) {
        return person.getName().toUpperCase();
    }
    return "UNKNOWN";
}

// With Optional
public String getName(Optional<Person> person) {
    return person
        .map(Person::getName)
        .map(String::toUpperCase)
        .orElse("UNKNOWN");
}

// Creating Optional
Optional<String> optional = Optional.of("Hello");
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(getValue());

// Using Optional
optional.ifPresent(System.out::println);
String value = optional.orElse("Default");
String computed = optional.orElseGet(() -> computeValue());

Design Patterns

Q37: What is Singleton pattern and how to implement it?

Singleton ensures only one instance of a class exists:

// Thread-safe Singleton using enum (recommended)
public enum SingletonEnum {
    INSTANCE;
    
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

// Double-checked locking
public class Singleton {
    private static volatile Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// Bill Pugh solution
public class SingletonBillPugh {
    private SingletonBillPugh() {}
    
    private static class SingletonHelper {
        private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
    }
    
    public static SingletonBillPugh getInstance() {
        return SingletonHelper.INSTANCE;
    }
}

Q38: What is Factory pattern?

Factory pattern creates objects without specifying exact classes:

// Product interface
interface Vehicle {
    void start();
}

// Concrete products
class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car started");
    }
}

class Bike implements Vehicle {
    @Override
    public void start() {
        System.out.println("Bike started");
    }
}

// Factory
class VehicleFactory {
    public static Vehicle createVehicle(String type) {
        switch (type.toLowerCase()) {
            case "car":
                return new Car();
            case "bike":
                return new Bike();
            default:
                throw new IllegalArgumentException("Unknown vehicle type");
        }
    }
}

// Usage
Vehicle vehicle = VehicleFactory.createVehicle("car");
vehicle.start();

Q39: What is Observer pattern?

Observer pattern defines one-to-many dependency between objects:

import java.util.*;

// Observer interface
interface Observer {
    void update(String message);
}

// Subject interface
interface Subject {
    void attach(Observer observer);
    void detach(Observer observer);
    void notifyObservers();
}

// Concrete subject
class NewsAgency implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String news;
    
    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }
    
    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    
    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(news);
        }
    }
    
    public void setNews(String news) {
        this.news = news;
        notifyObservers();
    }
}

// Concrete observer
class NewsSubscriber implements Observer {
    private String name;
    
    public NewsSubscriber(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

Spring Framework

Q40: What is Spring Framework and its benefits?

Spring is a comprehensive framework for Java enterprise development providing:

  • Dependency Injection: Loose coupling through IoC

  • Aspect-Oriented Programming: Cross-cutting concerns

  • Data Access: JDBC, ORM, transaction management

  • Web Development: MVC framework

  • Security: Authentication and authorization

  • Testing: Comprehensive testing support

Q41: What is Dependency Injection?

DI is a design pattern where dependencies are provided rather than created:

// Without DI - tight coupling
class OrderService {
    private PaymentService paymentService = new PaymentService();
    
    public void processOrder(Order order) {
        paymentService.processPayment(order.getAmount());
    }
}

// With DI - loose coupling
@Service
class OrderService {
    private final PaymentService paymentService;
    
    // Constructor injection (recommended)
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
    
    public void processOrder(Order order) {
        paymentService.processPayment(order.getAmount());
    }
}

@Service
class PaymentService {
    public void processPayment(double amount) {
        System.out.println("Processing payment: " + amount);
    }
}

Q42: What are Spring Bean scopes?

  • Singleton (default): One instance per Spring container

  • Prototype: New instance each time requested

  • Request: One instance per HTTP request

  • Session: One instance per HTTP session

  • Application: One instance per ServletContext

@Component
@Scope("prototype")
public class PrototypeBean {
    // New instance created each time
}

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SingletonBean {
    // Same instance reused
}

Continue: The Ultimate Java Interview Questions Guide 2025 : Part-3

Comments


bottom of page