JAVA INTERVIEW PREPARATION
Frequently Asked Questions with Real-time Examples and Code Snippets
Table of Contents
Q1. How does HashMap work internally?
Q2. Encapsulation with real-time explanation
Q3. Can I declare a class with abstract?
Q4. What is a default method?
Q5. Difference between @RequestParam and @QueryParam
Q1. How does HashMap work internally?
Answer: HashMap stores key-value pairs in buckets decided by hashCode(). Collisions are handled by linked list
(Java 7) or balanced tree (Java 8+).
Real-time Example: Like a dictionary: word (key) -> meaning (value).
import java.util.*;
public class HashMapDemo {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map.get("Apple"));
}
}
Q2. Encapsulation with real-time explanation
Answer: Encapsulation hides internal fields using private and exposes access via getters/setters.
Real-time Example: ATM: you deposit/withdraw but can’t access bank core system directly.
class BankAccount {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { balance += amt; }
}
Q3. Can I declare a class with abstract?
Answer: Yes, declaring a class as abstract means it cannot be instantiated and may contain abstract methods
(without implementation).
Real-time Example: A base class Vehicle that must be implemented by Car, Bike, etc.
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() { System.out.println("Car started"); }
}
Q4. What is a default method?
Answer: A default method is a method with an implementation in an interface. It allows interfaces to evolve
without breaking existing code.
Real-time Example: Java 8 introduced default methods to allow backward compatibility.
interface MyInterface {
default void greet() {
System.out.println("Hello from interface");
}
}
Q5. Difference between @RequestParam and @QueryParam
Answer: @RequestParam is used in Spring (maps query parameters), @QueryParam is used in JAX-RS (Java
EE). Both fetch data from URL query string.
Real-time Example: Spring: /users?name=Jana — use @RequestParam("name")
@GetMapping("/users")
public String getUser(@RequestParam String name) {
return "User: " + name;
}