Interview Prep
Interview Coding Questions Java — What Companies Actually Ask
Every tutorial gives you the same 50 Java questions with textbook answers. Here is what TCS, Flipkart, and Google India actually ask — and why most candidates still fail.

The gap between what tutorials teach and what interviewers ask is where most candidates fail.
The Real Java Interview Landscape
Java remains the most interviewed programming language in India. 90% of IT service company projects run on Java. Every major bank, insurance company, and telecom in India has Java at its core. When you search for “interview coding questions Java,” you get pages listing 100+ questions with copy-paste answers from the Java documentation. That is not how interviews work.
Real Java interviews test three things: can you write working code under pressure, do you understand why Java behaves the way it does (not just what it does), and can you solve problems that do not have a tutorial answer. The questions change dramatically based on where you are interviewing — a TCS interview and a Google India interview might both be “Java interviews” but they test completely different skills.
This guide is organized by company type because that is how the real world works. A fresher preparing for Infosys needs different preparation than someone targeting Flipkart. We will cover the actual questions, the thinking process interviewers expect, and the Java-specific traps that catch even experienced developers.
The interviewer does not care if you memorized the answer. They care if you can think through a problem they have not seen on GeeksforGeeks.
Service Company Questions (TCS, Infosys, Wipro, Cognizant)
Indian IT service companies test Java fundamentals — OOP concepts, String manipulation, Collections framework, and exception handling. They rarely ask LeetCode-style algorithm questions. The interview is 30–45 minutes and focuses on whether you understand core Java well enough to work on client projects from day one.
Q1: What happens when you modify a String in Java?
Why they ask: This tests whether you understand immutability — a concept that affects how you write production code, handle security, and manage memory.
What most candidates say: “Strings are immutable in Java.” Then they stop.
What the interviewer wants: Explain that when you “modify” a String, Java creates a new String object in the heap. The original remains unchanged. This is why concatenating Strings in a loop creates N objects and kills performance — you should use StringBuilder instead. Mention the String pool and how intern() works. If you can explain why Strings are immutable (thread safety, security for class loading, caching hashCode), you are ahead of 90% of candidates.
String s1 = "hello";
String s2 = s1.concat(" world"); // s1 is still "hello"
// s2 is a NEW object "hello world"
// In a loop, use StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i); // One object, not 1000
}Q2: Explain HashMap internals — how does put() actually work?
Why they ask: HashMap is the most used data structure in Java enterprise code. Understanding its internals separates developers who use it from developers who understand it.
The answer they want: HashMap uses an array of buckets. When you call put(key, value), Java calls key.hashCode(), applies a hash function to determine the bucket index, then stores the entry. If two keys hash to the same bucket (collision), entries are stored as a linked list in that bucket. Since Java 8, when a bucket exceeds 8 entries, the linked list converts to a balanced tree (red-black tree) for O(log n) lookup instead of O(n).
Follow-up trap: “What happens if you use a mutable object as a HashMap key and modify it after insertion?” Answer: the hashCode changes, so the entry becomes unretrievable from its original bucket. This is why String (immutable) is the most common HashMap key in practice.
Q3: Write code to find the second highest number in an array without sorting
Why they ask: This is the most common coding question at Indian service companies. It tests basic logic, edge case handling, and whether you can write clean code under pressure.
public static int secondHighest(int[] arr) {
if (arr.length < 2) throw new IllegalArgumentException("Need at least 2 elements");
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
if (second == Integer.MIN_VALUE) throw new RuntimeException("No second highest found");
return second;
}What separates good answers: Handling edge cases (array with all same elements, array with less than 2 elements), using Integer.MIN_VALUE instead of 0 as initial value, and explaining the O(n) time complexity.
Service Company Interview Pattern
Expect 3–5 conceptual questions (OOP, Collections, Exceptions, Multithreading basics) + 1–2 coding problems (String manipulation, array operations, basic pattern printing). Total time: 30–45 minutes. They test breadth, not depth. Knowing 20 topics at surface level beats knowing 5 topics deeply for these interviews.
Product Company Questions (Flipkart, Razorpay, Swiggy, Zerodha)
Indian product companies test data structures and algorithms implemented in Java. They do not care if you know the difference between HashMap and TreeMap — they care if you can use a HashMap to solve a problem in O(n) that a naive approach solves in O(n²). The interview is 45–60 minutes with 1–2 coding problems on a shared editor.
Q4: Given an array of integers, find two numbers that add up to a target sum
Why they ask: The classic Two Sum problem. It tests whether you can optimize from O(n²) brute force to O(n) using a HashMap — the fundamental pattern behind hundreds of interview problems.
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[] { seen.get(complement), i };
}
seen.put(nums[i], i);
}
throw new IllegalArgumentException("No solution found");
}What the interviewer evaluates: Did you jump to the optimal solution or start with brute force and optimize? Can you explain the time-space tradeoff (O(n) time, O(n) space vs O(n²) time, O(1) space)? Can you handle edge cases (duplicate values, negative numbers)?
Q5: Design an LRU Cache
Why they ask: This is the most asked system design + coding hybrid question at Indian product companies. It tests your understanding of LinkedHashMap, doubly linked lists, and how caching works in real systems.
class LRUCache {
private final int capacity;
private final LinkedHashMap<Integer, Integer> cache;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new LinkedHashMap<>(capacity, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};
}
public int get(int key) {
return cache.getOrDefault(key, -1);
}
public void put(int key, int value) {
cache.put(key, value);
}
}The follow-up: “Now implement it without using LinkedHashMap — use a HashMap + doubly linked list.” This is where the real test begins. Product companies want to see you build the data structure from scratch.
Product Company Interview Pattern
Expect 2 coding problems in 60 minutes — one medium, one medium-hard (LeetCode difficulty). You write code in a shared editor (CoderPad, HackerRank). They evaluate: problem-solving approach, code quality, edge case handling, and time/space complexity analysis. Java-specific knowledge is secondary — they care about your algorithmic thinking expressed in Java.

Product company interviews test how you think, not what you have memorized.
GCC / FAANG Questions (Google, Amazon, Microsoft India)
GCC interviews are the hardest Java coding interviews in India. They combine LeetCode hard-level problems with Java-specific system design questions. The bar is high — a 45-minute round expects you to understand the problem, design a solution, write clean code, test it, and analyze complexity. All while thinking out loud.
Q6: Find the median of a stream of integers
Why they ask: This tests your knowledge of heap data structures and your ability to maintain running statistics efficiently — a common requirement in real-time data processing systems.
class MedianFinder {
private PriorityQueue<Integer> maxHeap; // lower half
private PriorityQueue<Integer> minHeap; // upper half
public MedianFinder() {
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
if (minHeap.size() > maxHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() > minHeap.size()) return maxHeap.peek();
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
}What GCC interviewers evaluate: Can you explain why two heaps work? Can you prove the time complexity (O(log n) per insertion, O(1) for median)? What happens with integer overflow in the median calculation? Can you extend this to a sliding window median?
GCC Interview Pattern
4–5 rounds: 2 coding rounds (LeetCode medium-hard), 1 system design round (for experienced candidates), 1 behavioral round, and sometimes a Java deep-dive round testing JVM internals, concurrency, and memory management. Preparation time: 3–6 months of daily practice. The acceptance rate at Google India is under 1%.
Java-Specific Traps That Catch 70% of Candidates
These are not algorithm questions — they are Java behavior questions that test whether you truly understand the language. Interviewers love these because they cannot be solved by memorizing LeetCode patterns.
Trap 1: The equals() and hashCode() contract
“You have a class Employee with fields name and id. You put an Employee object in a HashSet. Then you change the employee's name. Can you still find it in the HashSet?”
The trap: If you override equals() but not hashCode() (or vice versa), HashSet and HashMap break silently. If you mutate an object after inserting it into a hash-based collection, the hashCode changes but the bucket does not — the object becomes a ghost that exists in the set but cannot be found.
The rule: If two objects are equal (equals() returns true), they must have the same hashCode(). Always override both together. Never mutate objects used as keys in hash-based collections.
Trap 2: ConcurrentModificationException
“What happens when you remove elements from an ArrayList while iterating over it with a for-each loop?”
// THIS THROWS ConcurrentModificationException:
for (String s : list) {
if (s.equals("remove")) list.remove(s); // BOOM
}
// CORRECT: Use Iterator.remove()
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("remove")) it.remove(); // Safe
}
// OR: Use removeIf() (Java 8+)
list.removeIf(s -> s.equals("remove")); // CleanestTrap 3: Integer caching — why == sometimes works for integers
Integer a = 127, b = 127; System.out.println(a == b); // true (cached) Integer c = 128, d = 128; System.out.println(c == d); // false (new objects!) // ALWAYS use .equals() for Integer comparison
Java caches Integer objects from -128 to 127. Within this range, == works because both variables point to the same cached object. Outside this range, new objects are created and == compares references, not values. This has caused real production bugs in banking software.
How to Actually Prepare for Java Coding Interviews
The preparation strategy depends entirely on your target company type. Here is a realistic plan for each:
For Service Companies (2–4 weeks)
Master Java fundamentals: OOP (inheritance, polymorphism, abstraction, encapsulation), Collections (ArrayList vs LinkedList, HashMap vs TreeMap, HashSet), Exception handling (checked vs unchecked, custom exceptions), String handling (immutability, StringBuilder, String pool), and basic multithreading (Thread vs Runnable, synchronized, volatile). Practice 20–30 coding problems on arrays, strings, and basic patterns. That is genuinely enough for TCS, Infosys, Wipro, and Cognizant.
For Product Companies (2–3 months)
Solve 150–200 LeetCode problems in Java — focus on arrays, strings, linked lists, trees, graphs, dynamic programming, and sliding window. Practice writing clean Java code under time pressure (35 minutes per medium problem). Learn Java-specific optimizations: when to use StringBuilder, how to use Comparator with PriorityQueue, how to leverage Java Streams for concise solutions. Mock interviews are essential — practice explaining your approach while coding.
For GCCs / FAANG (3–6 months)
Everything from the product company prep, plus: system design (design a URL shortener, design a chat system, design a rate limiter — all in Java), Java concurrency deep-dive (CompletableFuture, ExecutorService, ConcurrentHashMap, ReadWriteLock), JVM internals (garbage collection algorithms, memory model, class loading), and Java 17+ features (records, sealed classes, pattern matching). Solve 300+ LeetCode problems including hards. Do 10+ mock interviews with peers or platforms.
Practice With Real Interview Simulations
Reading questions is not the same as answering them under pressure. Practice with timed mock interviews that simulate real coding rounds — with feedback on your approach, code quality, and communication.
TRY INTERVIEW PRACTICE →The best Java interview preparation is not memorizing answers. It is solving problems you have never seen before, in Java, under a timer, while explaining your thinking out loud.
Java coding interviews reward preparation, not talent. The candidates who get offers are not the smartest — they are the ones who practiced the right problems for the right company type. Know your target, build a focused preparation plan, and practice under realistic conditions. The code you write in an interview is 50% of the evaluation. The other 50% is how you think, communicate, and handle problems you have not seen before.
Prepare for Your Java Interview
Practice with AI-powered mock interviews, get your resume ATS-ready, and walk into your next Java interview with confidence.
Free · AI-powered · Instant feedback
Related Reading
Resume Guide
Software Engineer Resume — India
Build a resume that gets you to the interview round
14 min read
Interview Prep
How to Answer “Tell Me About Yourself”
The question every interviewer asks first
9 min read
Resume Guide
Software Developer Resume — India
For freshers and service company developers
11 min read