36 practice questions with answers for Java interviews in Mumbai.
Java jobs in Mumbai
Mumbai is India's financial capital, so banks, fintechs, insurers, media and consulting firms drive much of the hiring. Data and QA interviews often include domain questions on payments, risk, trading or customer analytics.
Below are 36 questions that match the mix of service, product and domain employers hiring java developers in Mumbai.
Solved for MumbaiStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
Write a simple REST controller in Spring Boot for creating and fetching products.
HashMap gives O(1) average operations with no ordering guarantee. LinkedHashMap keeps insertion order, or access order if configured, which helps build an LRU cache. TreeMap keeps keys sorted by natural order or a Comparator with O(log n) operations and supports range methods like floorKey and headMap. HashMap allows one null key; TreeMap does not allow null keys with natural ordering.
03
Group a list of orders by city and sum the amount per city.
Use groupingBy with a summing collector.
Map<String, Double> totals = orders.stream()
.collect(Collectors.groupingBy(
Order::city,
TreeMap::new,
Collectors.summingDouble(Order::amount)));
TreeMap keeps cities sorted. For money, store amounts as long paise or BigDecimal and use Collectors.reducing with BigDecimal::add.
04
Count the frequency of each character in a string using Java.
A map with merge() is simple; streams also work.
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) {
freq.merge(c, 1, Integer::sum);
}
// Streams version
Map<Character, Long> f = s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c,
LinkedHashMap::new, Collectors.counting()));
LinkedHashMap keeps first-seen order.
05
What is the contract between equals() and hashCode()?
If two objects are equal by equals(), they must return the same hashCode(). Unequal objects may share a hash code, but fewer collisions give better performance. If you override equals() but not hashCode(), HashMap and HashSet break: an equal key lands in a different bucket and cannot be found. Use the same fields in both methods, or use records, which generate both.
06
What is the difference between static and dynamic binding?
Static binding is resolved at compile time and applies to private, static and final methods and to overloaded methods, because the compiler knows exactly which method to call. Dynamic binding is resolved at runtime based on the actual object type and applies to overridden instance methods. Static methods are hidden, not overridden, so the reference type decides which one runs.
07
What is a ClassLoader and what is the delegation model?
A ClassLoader loads .class files into the JVM. The main loaders are Bootstrap (core classes), Platform (formerly Extension) and Application (classpath). In the parent delegation model a loader first asks its parent to load a class and only loads it itself if the parent cannot. This prevents user code from replacing core classes like java.lang.String.
08
An API listing 100 orders fires 101 SQL queries. How do you fix it?
This is the N+1 problem from a lazy association loaded in a loop or by JSON serialisation. Fetch what the endpoint needs in one query with JOIN FETCH or @EntityGraph(attributePaths = "items"), or use a DTO projection query. For collections with pagination, fetch ids first, then fetch associations in a second query to avoid in-memory paging. Add a test that asserts the query count.
09
What is the difference between composition and inheritance, and which should you prefer?
Inheritance is an is-a relation where the subclass reuses parent code, but it creates tight coupling and fragile hierarchies. Composition is a has-a relation where a class holds another object and delegates work, such as a Car having an Engine. Prefer composition because it is flexible, allows changing behaviour at runtime and is easier to test. Use inheritance only for a true is-a relationship.
10
What is the difference between JPA, Hibernate and Spring Data JPA?
JPA, now Jakarta Persistence, is a specification of interfaces and annotations for object relational mapping. Hibernate is the most popular implementation of that specification and adds its own features. Spring Data JPA sits on top and generates repository implementations from interfaces and method names like findByEmail, reducing boilerplate. Your code uses JPA annotations, Hibernate does the work and Spring Data simplifies access.
Strings are immutable so they can be safely shared from the string pool, used as HashMap keys with a cached hash code, passed between threads without locking and trusted in security checks such as file paths and class names. Any change, like concat or replace, creates a new String. For heavy modification use StringBuilder, which changes its internal buffer in place.
12
Bind typed configuration properties with validation in Spring Boot.
Use a record with @ConfigurationProperties.
@ConfigurationProperties(prefix = "payment")
@Validated
public record PaymentProps(
@NotBlank String baseUrl,
@Min(100) int timeoutMs) {}
// application.yml
// payment:
// base-url: https://pay.internal
// timeout-ms: 2000
Enable it with @ConfigurationPropertiesScan on the main class. The app fails at startup if values are invalid.
13
toMap() throws Duplicate key exception in production. How do you fix it?
The data has repeated keys that the developer assumed were unique. Decide the business rule, then pass a merge function, for example toMap(User::email, u -> u, (a, b) -> a) to keep the first, or use groupingBy if all values are needed. Also check upstream data quality, since duplicates may signal a deeper bug such as missing unique constraints.
14
Write a record with validation in its compact constructor.
A compact constructor runs before fields are assigned.
public record Money(String currency, long paise) {
public Money {
Objects.requireNonNull(currency);
if (paise < 0) {
throw new IllegalArgumentException("negative amount");
}
}
public Money add(Money o) {
return new Money(currency, paise + o.paise);
}
}
Storing money in paise as long avoids floating point errors.
15
Implement equals() and hashCode() for an Employee class with id and email.
Use the same fields in both methods.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee e)) return false;
return id == e.id && Objects.equals(email, e.email);
}
@Override
public int hashCode() {
return Objects.hash(id, email);
}
Pattern matching for instanceof (Java 16) avoids an explicit cast.
16
Using streams, find the employee with the highest salary in each department.
Group by department with a maxBy downstream collector.
Map<String, Optional<Employee>> top = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
Collectors.maxBy(Comparator.comparingInt(Employee::salary))));
To get values without Optional, wrap with collectingAndThen(maxBy(...), Optional::get), which is safe because each group has at least one element.
17
How do you create a custom exception and when should you?
Extend RuntimeException for unchecked or Exception for checked, and provide constructors that accept a message and a cause so the root stack trace is kept. Create one when a domain error needs specific handling, such as InsufficientBalanceException, which a Spring @ControllerAdvice can map to an HTTP 422 response. Do not create exceptions for normal control flow.
18
A team member compares two Integer values with == and the check fails only for large numbers. Explain.
Integer.valueOf caches objects for values from -128 to 127, so autoboxed small numbers share the same object and == returns true. Larger values create new Integer objects, so == compares two different references and returns false. The fix is to use equals() or compare unboxed int values. Static analysis tools like SonarQube flag this pattern.
19
What are the four pillars of OOP? Explain with Java examples.
Encapsulation hides data behind methods, for example private fields with getters and setters in a BankAccount class. Abstraction exposes only what is needed through abstract classes or interfaces, like a Payment interface. Inheritance lets a class reuse another, such as SavingsAccount extends Account. Polymorphism lets one reference behave differently, like a Payment variable calling pay() on a UpiPayment or CardPayment.
20
How does JWT based authentication work in a Spring Boot API?
After login, the auth server issues a signed JWT with claims like user id, roles and expiry. The client sends it in the Authorization: Bearer header. The API, configured as an OAuth2 resource server in Spring Security, verifies the signature with the public key, checks expiry and builds the security context, so no session is needed. Keep tokens short-lived and use refresh tokens for renewal.
21
Tell me about a time you optimised a slow database query.
Situation: the customer search page took 6 seconds at peak. Task: bring it under 500 ms. Action: I captured the SQL, ran EXPLAIN ANALYZE and found a full scan due to LOWER(email) on an unindexed column and an N+1 on addresses. I added a functional index, fetched addresses with an entity graph and added pagination. Result: response time dropped to 180 ms and database CPU fell by a third.
String is immutable and thread safe by design. StringBuilder is mutable and not synchronized, so it is the fastest choice for building strings in a single thread, such as in loops. StringBuffer is mutable and synchronized, so it is thread safe but slower, and is rarely needed today. The compiler already optimises simple + concatenation outside loops.
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
24
Implement a producer-consumer using BlockingQueue.
Situation: a bulk upload feature had to go live in four days for a client launch. Task: build it safely in time. Action: I split it into must-have and later items, used an ExecutorService to process rows in parallel, wrote focused tests for validation and kept the product owner updated daily. Result: we shipped on time, it handled 50,000 rows in under two minutes and we added the extras next sprint.
26
How do you make sure database changes are released safely?
Situation: a manual schema change once broke our staging environment. Task: make migrations reliable. Action: I introduced Flyway with versioned scripts in the repo, required backward compatible changes such as adding nullable columns first, and ran migrations in CI against a test database. Result: we had zero failed migrations over the next year and rollbacks became predictable.
Method references are short forms of lambdas that just call an existing method. Types: static method (Integer::parseInt), instance method of a specific object (System.out::println), instance method of an arbitrary object of a type (String::toUpperCase) and constructor (ArrayList::new). They make stream code clearer when the lambda only forwards its arguments.
28
Find the second highest salary from a list of employees using streams.
Sort distinct salaries in descending order and skip one.
Optional<Integer> second = employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
This returns empty if fewer than two distinct salaries exist. For huge data a single pass tracking top two is O(n).
29
Run two tasks in parallel with CompletableFuture and combine their results.
ArrayList is backed by a resizable array, so get(i) is O(1) and appends are amortised O(1), but inserting in the middle shifts elements. LinkedList is a doubly linked list with O(n) random access but O(1) add or remove at the ends or through an iterator. In practice ArrayList is faster for almost all cases because of better CPU cache use; use ArrayDeque for queues.
31
What is the difference between an abstract class and an interface in modern Java?
An abstract class can have state (instance fields), constructors and any access modifier, and a class can extend only one. An interface has no instance state but, since Java 8, can have default and static methods, and since Java 9 private methods; a class can implement many. Use an interface for a capability contract and an abstract class to share code and state among closely related classes.
32
A file handle leak causes Too many open files errors after a day. What is the likely cause?
Streams, readers or connections are opened but not closed on all paths, especially when an exception is thrown before close(). Check with lsof or jcmd which files are open. Fix by wrapping every resource in try-with-resources so it always closes, and make sure Files.lines() and Files.list() streams are closed too, since they hold file handles.
It is public so the JVM can call it from outside the class, static so it can run without creating an object, and void because it returns nothing to the JVM; exit codes are set with System.exit(). The String[] args parameter receives command line arguments. From Java 21 onward, preview features allow simpler instance main methods for learning.
34
Tell me about a time you made a codebase more readable.
Situation: our reporting module had nested loops 200 lines long that new joiners feared. Task: make it maintainable without changing output. Action: I added snapshot tests on real report files, then refactored into small methods using streams, groupingBy and records for intermediate data, and reviewed each step with a teammate. Result: the module shrank by 40 percent and later changes took a day instead of a week.
35
When would you choose ArrayDeque over Stack and LinkedList?
Stack is a legacy synchronized class built on Vector, so it is slow and exposes index methods that break stack rules. LinkedList allocates a node per element. ArrayDeque is a resizable circular array with no per-element allocation, so push, pop, offer and poll are fast amortised O(1). Use ArrayDeque for both stacks and queues in single-threaded code; it does not accept null.
Fail-fast iterators, used by ArrayList and HashMap, throw ConcurrentModificationException if the collection is structurally modified during iteration other than through the iterator itself; they check a modCount. Fail-safe or weakly consistent iterators, as in ConcurrentHashMap and CopyOnWriteArrayList, work on a snapshot or tolerate changes and never throw, but may not show the latest updates.
Which companies hire Java professionals in Mumbai?
Companies with large offices in Mumbai include TCS, Accenture, Capgemini, LTIMindtree, Oracle, Goldman Sachs, JP Morgan Chase, Morgan Stanley, Barclays, Paytm. Use their company pages below to practise employer-specific sets.
Are Java interviews in Mumbai different from other cities?
The questions depend more on the company than the city. Mumbai's mix of employers decides the style: Data and QA interviews often include domain questions on payments, risk, trading or customer analytics
How do I find Java jobs in Mumbai?
Shortlist companies with Mumbai offices, keep your CV focused on Java projects, apply on company career pages and job portals with the Mumbai filter, and practise the questions on this page before each interview.