Core Java Questions
1. What are the key features of Java?
Answer:
- Object-Oriented
- Platform Independent (Write Once, Run Anywhere – WORA)
- Automatic Memory Management (Garbage Collection)
- Multi-threaded
- Secure
- High Performance (JIT Compiler)
- Robust (Exception Handling, Type Safety)
2. What is the difference between JDK, JRE, and JVM?
Answer:
- JDK (Java Development Kit): Includes JRE + development tools like compilers, debuggers.
- JRE (Java Runtime Environment): Includes JVM + libraries required to run Java applications.
- JVM (Java Virtual Machine): Converts Java bytecode into machine code.
3. What are the differences between == and .equals()?
Answer:
- == checks reference equality (whether both objects point to the same memory location).
- .equals() checks value equality (whether the contents of objects are the same).
Example:
String s1 = new String(“Hello”);
String s2 = new String(“Hello”);
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
4. What is the difference between ArrayList and LinkedList?
| Feature | ArrayList | LinkedList |
| Implementation | Uses dynamic array | Uses doubly linked list |
| Access Time | Fast (O(1) for index-based) | Slow (O(n) for index-based) |
| Insertion/Deletion | Slow (shifting required) | Fast (only pointer updates) |
| Memory Usage | Less (no extra pointers) | More (stores extra node pointers) |
5. What is the difference between HashMap and HashTable?
| Feature | HashMap | Hashtable |
| Thread Safety | Not synchronized | Synchronized |
| Performance | Faster | Slower |
| Null Keys/Values | Allows 1 null key, multiple null values | Doesn’t allow null keys/values |
| Inheritance | Implements Map | Extends Dictionary |
Object-Oriented Programming (OOP) Questions
6. Explain the four pillars of OOP.
Answer:
- Encapsulation: Hiding data using private variables and exposing it via public methods.
- Abstraction: Hiding implementation details, exposing only necessary information.
- Inheritance: Allows a class to acquire properties/methods of another class.
- Polymorphism: Allows a single method or operator to have multiple behaviors (method overloading, overriding).
7. What is method overloading and overriding?
Answer:
- Method Overloading (Compile-time polymorphism): Same method name, different parameter lists.
- Method Overriding (Run-time polymorphism): Child class redefines a method from the parent class.
Example:
class Parent {
void show() { System.out.println(“Parent class”); }
}
class Child extends Parent {
@Override
void show() { System.out.println(“Child class”); } // Overriding
}
Multithreading and Concurrency Questions
8. What are the differences between Runnable and Thread?
| Feature | Thread Class | Runnable Interface |
| Inheritance | Extends Thread (can’t extend another class) | Implements Runnable (can extend another class) |
| Reusability | Less reusable | More reusable |
| Preferred | Less preferred | More preferred |
Example:
class MyRunnable implements Runnable {
public void run() { System.out.println(“Thread running”); }
}
9. What is the difference between synchronized and volatile?
Answer:
- synchronized: Ensures atomicity and mutual exclusion.
- volatile: Ensures visibility of changes across threads but doesnโt guarantee atomicity.
Example:
volatile int counter = 0; // Ensures visibility across threads.
Spring Framework Questions
10. What is Dependency Injection in Spring?
Answer: Dependency Injection (DI) is a design pattern where dependencies are injected rather than created inside the class. Spring supports:
- Constructor Injection
- Setter Injection
- Field Injection (not recommended)
Example:
@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) { this.engine = engine; }
}
11. What is the difference between @Component, @Service, and @Repository?
| Annotation | Usage |
| @Component | Generic Spring-managed bean |
| @Service | Business logic layer component |
| @Repository | DAO (Data Access Object) component |
Database and Hibernate Questions
12. What is the difference between JPA, Hibernate, and JDBC?
| Feature | JDBC | Hibernate | JPA |
| Abstraction Level | Low | Medium | High |
| ORM Support | No | Yes | Yes |
| Query Language | SQL | HQL (Hibernate Query Language) | JPQL (Java Persistence Query Language) |
13. What is lazy loading and eager loading in Hibernate?
- Lazy Loading: Fetches data only when needed.
- Eager Loading: Fetches all related entities immediately.
Example:
@OneToMany(fetch = FetchType.LAZY) // Lazy loading
private List<Orders> orders;
Advanced Java & Design Patterns Questions
14. What are the design patterns used in Java?
Common Design Patterns:
- Singleton: Ensures only one instance of a class exists.
- Factory: Creates objects dynamically based on conditions.
- Builder: Helps in constructing complex objects step by step.
- Observer: Notifies objects when state changes.
15. How do you prevent creating multiple instances of a Singleton class?
public class Singleton {
private static Singleton instance;
private Singleton() {} // Private constructor
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Coding Challenges (Data Structures & Algorithms)
These coding problems test your problem-solving and algorithmic thinking skills.
1. Reverse a String in Java
Problem: Write a function to reverse a given string without using built-in methods.
Solution:
public class ReverseString {
public static String reverse(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = str.length() – 1; i >= 0; i–) {
reversed.append(str.charAt(i));
}
return reversed.toString();
}
public static void main(String[] args) {
System.out.println(reverse(“hello”)); // Output: olleh
}
}
Alternative Solution using Recursion:
public class ReverseStringRec {
public static String reverse(String str) {
if (str.isEmpty()) return str;
return reverse(str.substring(1)) + str.charAt(0);
}
}
2. Find the First Non-Repeating Character in a String
Problem: Given a string, return the first character that appears only once.
Solution:
import java.util.*;
public class FirstUniqueChar {
public static char firstUniqueChar(String str) {
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() == 1) return entry.getKey();
}
return ‘_’; // No unique character
}
public static void main(String[] args) {
System.out.println(firstUniqueChar(“swiss”)); // Output: w
}
}
3. Find Duplicates in an Array
import java.util.*;
public class FindDuplicates {
public static List<Integer> findDuplicates(int[] nums) {
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
duplicates.add(num);
}
}
return new ArrayList<>(duplicates);
}
}
4. Detect a Cycle in a Linked List (Floydโs Cycle Detection Algorithm)
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class CycleDetection {
public static boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}
5. Find the Longest Substring Without Repeating Characters
import java.util.*;
public class LongestSubstring {
public static int longestUniqueSubstring(String s) {
Map<Character, Integer> charIndex = new HashMap<>();
int maxLength = 0, left = 0;
for (int right = 0; right < s.length(); right++) {
if (charIndex.containsKey(s.charAt(right))) {
left = Math.max(left, charIndex.get(s.charAt(right)) + 1);
}
charIndex.put(s.charAt(right), right);
maxLength = Math.max(maxLength, right – left + 1);
}
return maxLength;
}
}
System Design Questions for Java Developers
These questions assess your ability to design scalable, high-performance applications.
1. Design a URL Shortener (like bit.ly)
๐ก Requirements:
- Shorten long URLs.
- Handle high read/write requests.
- Generate unique short links.
๐น Solution Approach:
- Use Base62 encoding (characters [a-zA-Z0-9]) to create a short URL.
- Store mappings in a database (SQL/NoSQL).
- Use caching (Redis) for fast lookups.
Sample Code:
import java.util.*;
public class URLShortener {
private static final String BASE62 = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
private static final int BASE = BASE62.length();
private static final Map<String, String> urlMap = new HashMap<>();
private static int counter = 1;
public static String encode(String longUrl) {
String shortUrl = base62Encode(counter++);
urlMap.put(shortUrl, longUrl);
return shortUrl;
}
public static String decode(String shortUrl) {
return urlMap.get(shortUrl);
}
private static String base62Encode(int num) {
StringBuilder sb = new StringBuilder();
while (num > 0) {
sb.append(BASE62.charAt(num % BASE));
num /= BASE;
}
return sb.reverse().toString();
}
}
2. Design a Rate Limiter (API Throttling)
๐ก Solution Approach:
- Use Token Bucket Algorithm or Leaky Bucket Algorithm.
- Implement with Redis or Guava RateLimiter.
Java Implementation:
import java.util.concurrent.*;
public class RateLimiter {
private final int maxRequests;
private final long timeWindowMillis;
private final Deque<Long> requestTimestamps = new ConcurrentLinkedDeque<>();
public RateLimiter(int maxRequests, long timeWindowMillis) {
this.maxRequests = maxRequests;
this.timeWindowMillis = timeWindowMillis;
}
public synchronized boolean allowRequest() {
long now = System.currentTimeMillis();
while (!requestTimestamps.isEmpty() && now – requestTimestamps.peekFirst() > timeWindowMillis) {
requestTimestamps.pollFirst();
}
if (requestTimestamps.size() < maxRequests) {
requestTimestamps.addLast(now);
return true;
}
return false;
}
}
Behavioral & Project-Based Questions
Apart from technical questions, interviewers often ask about your experience in real-world projects.
1. Can you describe a complex Java-based project you worked on?
๐น How to Answer:
- Use the STAR Method (Situation, Task, Action, Result).
- Focus on problem-solving, scalability, and technologies used.
Example: “I worked on an enterprise-grade CRM system where we needed to process millions of customer records efficiently. We used Spring Boot, Hibernate, and PostgreSQL for the backend. To optimize performance, I implemented caching with Redis and used asynchronous processing with Kafka, reducing response time by 40%.”
2. How do you optimize Java applications for performance?
๐น Possible Approaches:
- Use profiling tools (JProfiler, VisualVM) to find bottlenecks.
- Optimize Garbage Collection (GC tuning).
- Use multithreading for parallel processing.
- Optimize SQL queries and use caching.
Final Interview Tips
โ Be thorough with Java fundamentals (OOP, Collections, Multithreading, Exception Handling).
โ Understand frameworks like Spring and Hibernate.
โ Practice coding problems on data structures & algorithms.
โ Prepare for real-world scenarios (system design, microservices).
โ
Practice coding problems daily on LeetCode, HackerRank, or CodeSignal.
โ
Be comfortable with design patterns, multithreading, and memory management.
โ
Be ready to discuss real-world Java projects.
โ
Understand microservices, REST APIs, and database optimization.