Skip to content

Java Interview Questions in Chennai

36 practice questions with answers for Java interviews in Chennai.

Java jobs in Chennai

Chennai is a long-standing IT-services and SaaS hub along OMR, with strong demand for testing, data and support-engineering roles. Many companies here hire freshers in large batches and train them on the job.

Below are 36 questions that match the mix of service, product and domain employers hiring java developers in Chennai.

Solved for ChennaiStart 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

What is the N+1 select problem in Hibernate and how do you fix it?

Save to ▾
Show answer
N+1 happens when you load N parent entities with one query and then a lazy association triggers one extra query per parent, giving N+1 queries. Fix it with a JOIN FETCH in JPQL, an @EntityGraph on the repository method, or batch fetching with @BatchSize or hibernate.default_batch_fetch_size. Detect it by enabling SQL logging or using a query count assertion in tests.
02

What is the difference between an abstract class and an interface in modern Java?

Save to ▾
Show answer
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.
03

What is the difference between lazy and eager loading?

Save to ▾
Show answer
Lazy loading fetches an association only when it is first accessed, using a proxy; eager loading fetches it immediately with the parent. In JPA, @ManyToOne and @OneToOne default to EAGER, while @OneToMany and @ManyToMany default to LAZY. Best practice is to make all associations lazy and fetch what each use case needs with JOIN FETCH or entity graphs, which avoids loading huge object graphs.
04

Write a Java program to check whether a number is prime.

Save to ▾
Show answer
Check divisibility only up to the square root, which makes it O(sqrt n). public static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (int i = 3; (long) i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } The long cast avoids overflow for large n.
05

Tell me about a time you optimised a slow database query.

Save to ▾
Show answer
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.
06

What is the difference between Collectors.toMap() and groupingBy()?

Save to ▾
Show answer
toMap() creates one entry per element using key and value functions and throws IllegalStateException on duplicate keys unless you give a merge function. groupingBy() collects all elements with the same key into a List by default, or applies a downstream collector like counting or summingInt. Use toMap for unique keys like id and groupingBy for categories like city.
07

What are the ways to create a thread in Java?

Save to ▾
Show answer
You can extend Thread and override run(), or implement Runnable or Callable and pass it to a Thread or an ExecutorService. Callable returns a result and can throw checked exceptions, giving a Future. Modern code rarely creates threads directly; it uses executors, CompletableFuture or, from Java 21, virtual threads with Thread.ofVirtual().start(task).
08

Write code that runs 10,000 blocking tasks using virtual threads.

Save to ▾
Show answer
Use the virtual-thread-per-task executor in Java 21. try (var ex = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 10_000; i++) { int id = i; ex.submit(() -> { Thread.sleep(Duration.ofMillis(200)); return id; }); } } // close() waits for all tasks All tasks finish in about 200 ms because blocked virtual threads free their carriers.
09

What is the difference between final, finally and finalize?

Save to ▾
Show answer
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try-catch whether or not an exception occurs, used for cleanup. finalize() was a method called before garbage collection; it is deprecated for removal and should be replaced with try-with-resources or Cleaner.
10

Why does Java not support multiple inheritance of classes?

Save to ▾
Show answer
Multiple inheritance of classes creates the diamond problem: if two parents have the same method with different code, the child cannot know which one to use, and state duplication becomes messy. Java avoids this by allowing one superclass but many interfaces. If two interfaces provide the same default method, the class must override it and can call a specific one with InterfaceName.super.method().
11

Write code to check if two strings are anagrams.

Save to ▾
Show answer
Count characters with an array for lowercase letters. public static boolean isAnagram(String a, String b) { if (a.length() != b.length()) return false; int[] count = new int[26]; for (int i = 0; i < a.length(); i++) { count[a.charAt(i) - 'a']++; count[b.charAt(i) - 'a']--; } for (int c : count) if (c != 0) return false; return true; } O(n) time; use a HashMap for Unicode input.
12

Implement the Builder pattern for a User class with many optional fields.

Save to ▾
Show answer
A builder avoids long constructors. public class User { private final String name; private final int age; private User(Builder b) { name = b.name; age = b.age; } public static class Builder { private String name; private int age; public Builder name(String n) { name = n; return this; } public Builder age(int a) { age = a; return this; } public User build() { return new User(this); } } } Usage: new User.Builder().name("Asha").age(25).build(). Lombok @Builder generates this.
13

What is the difference between synchronized and ReentrantLock?

Save to ▾
Show answer
synchronized is a built-in keyword that locks a monitor and releases it automatically at block exit. ReentrantLock is an explicit lock that adds tryLock with timeout, interruptible locking, fairness options and multiple Condition objects, but you must unlock in a finally block. Both are reentrant. Prefer synchronized for simple cases and ReentrantLock when you need its extra features.
14

Explain pattern matching for switch and record patterns in Java 21.

Save to ▾
Show answer
Pattern matching for switch lets a case match on type and bind a variable, such as case Circle c -> Math.PI * c.r() * c.r(). Record patterns deconstruct a record directly: case Point(int x, int y). Guards add conditions with when. With sealed types the compiler checks the switch is exhaustive, so adding a new subtype causes a compile error where it is not handled.
15

Write a unit test for a service class using JUnit 5 and Mockito.

Save to ▾
Show answer
Mock the repository and verify behaviour. @ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock ProductRepository repo; @InjectMocks ProductService service; @Test void throwsWhenMissing() { when(repo.findById(1L)).thenReturn(Optional.empty()); assertThrows(NotFoundException.class, () -> service.get(1L)); verify(repo).findById(1L); } } No Spring context starts, so the test runs in milliseconds.
16

How does @Transactional work and what are its common pitfalls?

Save to ▾
Show answer
@Transactional is applied through a proxy that opens a transaction before the method and commits or rolls back after. Pitfalls: calling a transactional method from the same class bypasses the proxy, so no transaction starts; by default rollback happens only for unchecked exceptions; it works on public methods; and long transactions with remote calls hold connections. Use propagation and readOnly where suitable.
17

What is the difference between reduce() and collect()?

Save to ▾
Show answer
reduce() combines elements into a single immutable value using an identity and an associative function, such as summing numbers. collect() is a mutable reduction that accumulates into a container like a List, Map or StringBuilder, which is far more efficient for building collections. Using reduce to build a list creates many intermediate copies, so use collect for containers.
18

A query is fast in development but takes 8 seconds in production. How do you investigate?

Save to ▾
Show answer
Production has more data, so check the execution plan with EXPLAIN ANALYZE on production-like data. Look for full table scans, missing indexes on filter or join columns, functions on indexed columns and poor statistics. Check if Hibernate generates the SQL you expect. Add a suitable composite index, rewrite the query or paginate, and verify the plan improves before release.
19

What is the Liskov Substitution Principle? Give an example of breaking it.

Save to ▾
Show answer
LSP says any subclass object must be usable wherever the parent is expected without breaking behaviour. A classic violation is Square extends Rectangle: setting width also changes height, so code that sets width 5 and height 4 and expects area 20 fails. Another is a subclass throwing UnsupportedOperationException for a parent method. The fix is a better hierarchy or composition.
20

Tell me about a time a production incident happened because of your code.

Save to ▾
Show answer
Situation: a release I made caused failed payments for some users. Task: restore service and find the cause fast. Action: I rolled back within ten minutes, then found I had not handled a null bank code from one partner, which threw an exception. I fixed it, added validation and a test with that partner's data and shared a short write-up. Result: no repeat and the team added null checks to our review checklist.
21

Explain the SOLID principles briefly.

Save to ▾
Show answer
Single Responsibility: a class has one reason to change. Open/Closed: open for extension, closed for modification. Liskov Substitution: subclasses must work wherever the parent is expected. Interface Segregation: prefer small, focused interfaces. Dependency Inversion: depend on abstractions, not concrete classes. Spring dependency injection is a practical example of dependency inversion.
22

Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?

Save to ▾
Show answer
A typical command is: java -Xms4g -Xmx4g \ -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \ -XX:+HeapDumpOnOutOfMemoryError \ -XX:HeapDumpPath=/var/log/app \ -Xlog:gc*:file=/var/log/app/gc.log \ -jar app.jar In containers prefer -XX:MaxRAMPercentage=75 so the heap follows the container memory limit.
23

You must expose configuration that differs between dev, QA and production. How do you manage it?

Save to ▾
Show answer
Use Spring profiles with application-dev.yml and application-prod.yml, and bind settings to typed @ConfigurationProperties classes with validation. Keep secrets out of the repo by injecting them through environment variables, Kubernetes Secrets or a vault. Activate the profile with SPRING_PROFILES_ACTIVE in each environment. Use the same build artefact everywhere and change only configuration.
24

Run two tasks in parallel with CompletableFuture and combine their results.

Save to ▾
Show answer
Use a dedicated executor for I/O work. ExecutorService pool = Executors.newFixedThreadPool(4); CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userApi.get(id), pool); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderApi.list(id), pool); Profile p = user.thenCombine(orders, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .join();
25

An API listing 100 orders fires 101 SQL queries. How do you fix it?

Save to ▾
Show answer
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.
26

Show runtime polymorphism with a simple Java example.

Save to ▾
Show answer
A parent reference calls the child's overridden method at runtime. abstract class Shape { abstract double area(); } class Circle extends Shape { double r = 2; double area() { return Math.PI * r * r; } } class Square extends Shape { double s = 3; double area() { return s * s; } } Shape sh = new Circle(); System.out.println(sh.area()); // Circle area
27

Describe a time you improved the design of existing code.

Save to ▾
Show answer
Situation: our notification module used a 400 line class with switch cases for email, SMS and WhatsApp. Task: add push notifications without breaking anything. Action: I wrote tests for current behaviour, extracted a Notifier interface with one class per channel and used Spring to inject them by type. Result: push was added in one new class, bugs in that module dropped and new channels now take hours, not days.
28

Using streams, find the employee with the highest salary in each department.

Save to ▾
Show answer
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.
29

Find the second highest salary from a list of employees using streams.

Save to ▾
Show answer
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).
30

Map a one-to-many relation between Order and OrderItem in JPA.

Save to ▾
Show answer
Make the child own the foreign key and keep both sides in sync. @Entity class Order { @Id @GeneratedValue Long id; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) List<OrderItem> items = new ArrayList<>(); void addItem(OrderItem i) { items.add(i); i.setOrder(this); } } @Entity class OrderItem { @Id @GeneratedValue Long id; @ManyToOne(fetch = FetchType.LAZY) Order order; }
31

What is the difference between method overloading and method overriding?

Save to ▾
Show answer
Overloading means several methods in the same class share a name but differ in parameter list; it is resolved at compile time. Overriding means a subclass provides its own version of a parent method with the same signature; it is resolved at runtime through dynamic dispatch. Return type alone cannot overload a method, while overriding allows a covariant return type.
32

What is a functional interface?

Save to ▾
Show answer
A functional interface has exactly one abstract method, so it can be implemented with a lambda or method reference. It may also have default and static methods. Examples are Runnable, Comparator, and those in java.util.function: Function, Predicate, Consumer, Supplier and BiFunction. The @FunctionalInterface annotation makes the compiler enforce the single abstract method rule.
33

Two users booking the last seat both succeed. How do you prevent double booking?

Save to ▾
Show answer
This is a race between read and write. Use a database guarantee: a unique constraint on seat and show, an atomic conditional update like UPDATE seats SET status = 'BOOKED' WHERE id = ? AND status = 'FREE' and check the affected row count, or pessimistic locking with SELECT FOR UPDATE. Optimistic locking with a version column also works, retrying or failing the loser.
34

Write a record with validation in its compact constructor.

Save to ▾
Show answer
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.
35

What does the var keyword do and where can it not be used?

Save to ▾
Show answer
var, added in Java 10, lets the compiler infer the type of a local variable from its initializer, for example var list = new ArrayList<String>(). Java stays statically typed. var cannot be used for fields, method parameters or return types, and it needs an initializer that is not null. Use it when the type is obvious to keep code readable.
36

Users get LazyInitializationException when the API returns an entity. What is happening?

Save to ▾
Show answer
The entity was loaded inside a transaction, the session closed, and then Jackson touched a lazy association outside it. Do not fix it by turning on open-session-in-view or making everything eager. Instead, map the entity to a DTO inside the service transaction and fetch needed associations explicitly with JOIN FETCH or an entity graph. Spring Boot logs a warning because open-in-view is on by default.

Companies with offices in Chennai (11)

Frequently asked questions

Which companies hire Java professionals in Chennai?

Companies with large offices in Chennai include TCS, Infosys, Wipro, Cognizant, Capgemini, HCLTech, Tech Mahindra, LTIMindtree, Amazon, Barclays. Use their company pages below to practise employer-specific sets.

Are Java interviews in Chennai different from other cities?

The questions depend more on the company than the city. Chennai's mix of employers decides the style: Many companies here hire freshers in large batches and train them on the job

How do I find Java jobs in Chennai?

Shortlist companies with Chennai offices, keep your CV focused on Java projects, apply on company career pages and job portals with the Chennai filter, and practise the questions on this page before each interview.