Skip to content

Java Interview Questions in Coimbatore

36 practice questions with answers for Java interviews in Coimbatore.

Java jobs in Coimbatore

Coimbatore has a growing IT-services and engineering-services market around TIDEL Park and its SEZs, supported by a large pool of engineering graduates. Many roles are with delivery centres of bigger IT firms.

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

Solved for CoimbatoreStart 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 Spring Boot and how is it different from the Spring Framework?

Save to ▾
Show answer
Spring Framework provides dependency injection, MVC, transactions and data access but needs manual configuration. Spring Boot builds on it with auto-configuration, starter dependencies, an embedded server such as Tomcat and production features through Actuator, so you can run a service with java -jar. Spring Boot 3 requires Java 17 or later and uses Jakarta EE packages instead of javax.
02

How do you make a class immutable in Java?

Save to ▾
Show answer
Declare the class final, make all fields private and final, set them only in the constructor, and provide no setters. For mutable fields like a List or Date, make defensive copies in the constructor and in getters, or use List.copyOf. Immutable objects are thread safe and make good map keys. Java records give a concise way to create shallowly immutable data classes.
03

Write a JDBC method to fetch a user by email safely.

Save to ▾
Show answer
Use a PreparedStatement and try-with-resources. public Optional<User> findByEmail(String email) throws SQLException { String sql = "SELECT id, name FROM users WHERE email = ?"; try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { ps.setString(1, email); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) return Optional.of(new User(rs.getLong(1), rs.getString(2))); } } return Optional.empty(); }
04

Compare the G1, ZGC and Parallel garbage collectors.

Save to ▾
Show answer
Parallel GC focuses on throughput and uses multiple threads but stops the application during collection. G1, the default since Java 9, splits the heap into regions and targets a pause time goal, which suits most server apps. ZGC is a low latency collector with pauses typically under a millisecond even on very large heaps, and is generational from Java 21. Choose based on latency versus throughput needs.
05

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.
06

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.
07

How do you create a custom exception and when should you?

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

Does the finally block always execute?

Save to ▾
Show answer
finally runs after try and catch in almost every case, including when the try block returns or throws. It does not run if the JVM exits through System.exit(), the process is killed or the thread dies abruptly. Avoid returning from finally, because that silently overrides the try block's return value and swallows exceptions.
09

What is garbage collection and how does the JVM decide an object is garbage?

Save to ▾
Show answer
Garbage collection automatically frees memory used by objects that are no longer reachable. The JVM starts from GC roots such as local variables on thread stacks, static fields and active threads, and marks every object reachable from them. Anything not marked is garbage. Because reachability is used rather than reference counting, circular references between unreachable objects are still collected.
10

A counter shared between threads shows wrong totals. How do you fix it?

Save to ▾
Show answer
count++ is not atomic; two threads can read the same value and both write the same result, so updates are lost. Use AtomicInteger.incrementAndGet(), which uses CAS, or LongAdder for very high contention, as it spreads updates over cells. A synchronized method also works but is slower. volatile alone does not fix it because it gives visibility, not atomicity.
11

What is the difference between HashMap and ConcurrentHashMap?

Save to ▾
Show answer
HashMap is not thread safe; concurrent writes can lose data or corrupt the structure. ConcurrentHashMap supports full concurrency: reads are lock free and writes use CAS or lock a single bin, so threads rarely block each other. It does not allow null keys or values. It also provides atomic compound operations such as computeIfAbsent and merge, which avoid check-then-act races.
12

What is a deadlock and how can it be prevented?

Save to ▾
Show answer
A deadlock happens when two or more threads each hold a lock and wait for a lock held by the other, so none can continue. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always acquiring locks in the same global order, using tryLock with a timeout, holding locks briefly and avoiding calls to unknown code while holding a lock.
13

Users report the app is slow for the first few minutes after every deployment. Why might this happen?

Save to ▾
Show answer
This is usually JVM warm-up. Code runs in the interpreter until the JIT compiles hot paths, and caches, connection pools and class loading are also cold. Fixes include warm-up traffic before adding the instance to the load balancer, pre-initialising pools, class data sharing (AppCDS) to reduce start time, or newer options like CRaC or GraalVM native image when fast start is critical.
14

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.
15

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.
16

Describe a time you had to learn a new technology quickly.

Save to ▾
Show answer
Situation: I joined a project using reactive Spring WebFlux with no prior experience. Task: contribute within two weeks. Action: I studied Project Reactor basics, built a small practice service, paired with a senior on my first ticket and kept notes on common operators. Result: I delivered my first feature in the second week and later wrote the team guide on avoiding blocking calls in reactive code.
17

What is Optional and how should it be used?

Save to ▾
Show answer
Optional is a container that may or may not hold a value, used mainly as a method return type to show that a result can be absent, for example findById. Use map, filter, orElse, orElseGet and orElseThrow instead of calling get() blindly. Do not use Optional for fields, parameters or collections, and prefer orElseGet when the default is costly to create.
18

How does HashMap work internally?

Save to ▾
Show answer
HashMap stores entries in an array of buckets. It computes the key's hashCode(), spreads the bits and picks a bucket index. Collisions are stored as a linked list in the bucket, and since Java 8 a bucket with more than 8 entries (when the table has at least 64 buckets) becomes a red-black tree, making the worst case O(log n). When size passes capacity times load factor 0.75, it resizes to double.
19

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.
20

A getter returns an internal List and callers modify it, causing bugs. How do you fix this?

Save to ▾
Show answer
This breaks encapsulation. Return an unmodifiable view with Collections.unmodifiableList(list) or a copy with List.copyOf(list), so callers cannot change internal state. Also copy the list passed into the constructor or setter. If the class should be fully immutable, store List.copyOf in a final field. Expose specific methods like addItem() when controlled changes are needed.
21

Write a minimal Dockerfile for a Spring Boot application.

Save to ▾
Show answer
A multi-stage build keeps the image small. FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
22

What are sealed classes and how do they help?

Save to ▾
Show answer
Sealed classes and interfaces, final in Java 17, restrict which classes can extend them using the permits clause, for example sealed interface Shape permits Circle, Square. Each subclass must be final, sealed or non-sealed. This models a closed set of types, and with pattern matching for switch in Java 21 the compiler can check that every case is handled without a default branch.
23

Print numbers 1 to 10 alternately from two threads (odd and even).

Save to ▾
Show answer
Use a shared lock with wait and notify. class Printer { int n = 1; synchronized void print(boolean odd) throws InterruptedException { while (n <= 10) { if ((n % 2 == 1) == odd) { System.out.println(Thread.currentThread().getName() + " " + n++); notifyAll(); } else wait(); } notifyAll(); } } Start one thread with print(true) and another with print(false).
24

How would you write a simple thread safe rate limiter in Java?

Save to ▾
Show answer
A token bucket with synchronized refill is simple and correct. class RateLimiter { private final long capacity, refillPerSec; private double tokens; private long last = System.nanoTime(); RateLimiter(long cap, long rps) { capacity = cap; refillPerSec = rps; tokens = cap; } synchronized boolean tryAcquire() { long now = System.nanoTime(); tokens = Math.min(capacity, tokens + (now - last) / 1e9 * refillPerSec); last = now; if (tokens >= 1) { tokens--; return true; } return false; } } Across servers, keep the bucket in Redis.
25

An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?

Save to ▾
Show answer
Since the calls are independent, run them in parallel with CompletableFuture.supplyAsync on a dedicated executor or with virtual threads, then join with allOf. Total latency becomes roughly the slowest call, about 300 ms. Add a timeout per call with orTimeout and a fallback for failures so one slow service does not block the whole response. Structured concurrency is another option in newer Java.
26

Write a Kafka producer and consumer in Spring Boot.

Save to ▾
Show answer
Spring Kafka hides most boilerplate. @Service class OrderEvents { private final KafkaTemplate<String, OrderPlaced> kafka; OrderEvents(KafkaTemplate<String, OrderPlaced> k) { kafka = k; } void publish(OrderPlaced e) { kafka.send("orders", e.orderId(), e); } } @Component class OrderListener { @KafkaListener(topics = "orders", groupId = "inventory") void on(OrderPlaced e) { inventory.reserve(e); } } Using orderId as key keeps events for one order in the same partition and order.
27

What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?

Save to ▾
Show answer
List.of() returns a truly immutable list; add, set and remove throw exceptions and nulls are not allowed. Arrays.asList() returns a fixed-size list backed by the array: set() works and writes through to the array, but add() and remove() throw. Collections.unmodifiableList() is a read-only view, so changes to the original list are still visible through it.
28

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.
29

Explain bean scopes in Spring.

Save to ▾
Show answer
singleton is the default: one instance per application context. prototype creates a new instance each time it is requested. Web scopes include request, session and application. Singletons must be stateless or thread safe because all requests share them. Injecting a prototype into a singleton gives only one instance, so use ObjectProvider or a scoped proxy to get fresh ones.
30

Why is PreparedStatement preferred over Statement?

Save to ▾
Show answer
PreparedStatement sends the SQL with placeholders separately from the parameter values, so user input is never treated as SQL, which prevents SQL injection. The database can also cache and reuse the execution plan, and it handles types like dates correctly. Statement with string concatenation is unsafe and slower for repeated queries, so it should not be used with user input.
31

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; }
32

Remove duplicates from a list while keeping the original order.

Save to ▾
Show answer
A LinkedHashSet keeps first-seen order. List<String> unique = new ArrayList<>(new LinkedHashSet<>(names)); // or with streams List<String> unique2 = names.stream() .distinct() .toList(); Both rely on equals() and hashCode(), and both run in O(n) on average.
33

How do you prepare for coding rounds as a Java developer?

Save to ▾
Show answer
Situation: I was preparing for product company interviews while working. Task: get strong at DSA in limited time. Action: I solved two problems a day by pattern, such as sliding window and graphs, always in Java with Collections, timed myself and reviewed mistakes every weekend. Result: in three months I solved 250 problems, cleared online tests comfortably and could explain time complexity clearly.
34

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.
35

Implement an LRU cache using LinkedHashMap.

Save to ▾
Show answer
Access order plus removeEldestEntry gives LRU in a few lines. class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; LruCache(int capacity) { super(16, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > capacity; } } get and put are O(1).
36

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.

Few big employers listed in Coimbatore?

Many Coimbatore candidates also apply to teams in Chennai and to remote or hybrid roles. Practise the Chennai set as well.

Frequently asked questions

Which companies hire Java professionals in Coimbatore?

Companies with large offices in Coimbatore include many IT services and product firms. Use their company pages below to practise employer-specific sets.

Are Java interviews in Coimbatore different from other cities?

The questions depend more on the company than the city. Coimbatore's mix of employers decides the style: Many roles are with delivery centres of bigger IT firms

How do I find Java jobs in Coimbatore?

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