36 practice questions with answers for Java interviews in Chandigarh.
Java jobs in Chandigarh
Chandigarh, Mohali and Panchkula form the Tricity IT cluster, with IT-services firms, SaaS companies and start-ups in Mohali's IT City and Chandigarh's IT Park. Interviews usually check strong fundamentals and practical tool skills.
Below are 36 questions that match the mix of service, product and domain employers hiring java developers in Chandigarh.
Solved for ChandigarhStart 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 code that runs 10,000 blocking tasks using virtual threads.
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.
02
What is the difference between ArrayList and LinkedList?
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.
03
A HashMap shared by many threads sometimes loses updates. How do you fix it?
HashMap is not thread safe, so concurrent put calls can overwrite each other. Replace it with ConcurrentHashMap and use atomic methods instead of get-then-put, for example counts.merge(key, 1, Integer::sum) or computeIfAbsent for lazy creation. Collections.synchronizedMap also works but locks the whole map, which hurts throughput under contention.
04
Find the first non-repeating character in a string.
Count in one pass, then scan again in order.
public static char firstUnique(String s) {
int[] cnt = new int[128];
for (char c : s.toCharArray()) cnt[c]++;
for (char c : s.toCharArray()) {
if (cnt[c] == 1) return c;
}
return '_';
}
Two passes, O(n) time and O(1) extra space for ASCII input.
05
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.
06
How do you handle a situation where you made a wrong technical decision?
Situation: I chose eager loading for a reporting entity to save time, and later pages became slow. Task: own and fix it. Action: I told my lead, measured the impact, switched associations to lazy with targeted fetch joins and added query count tests. Result: performance recovered within a sprint and I now review fetch strategy in every design discussion.
07
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.
start() asks the JVM to create a new thread and then calls run() on that new thread, so the code executes concurrently. Calling run() directly is just a normal method call on the current thread, so no new thread is created. Calling start() twice on the same Thread throws IllegalThreadStateException.
09
A stream pipeline that updates a shared ArrayList in forEach gives random results with parallel(). Why?
ArrayList is not thread safe, and parallel streams run forEach on many threads, so additions race, get lost or throw exceptions. Side effects in streams are the problem. Replace forEach with collect(Collectors.toList()) or toList(), which handles merging per thread safely. Keep lambdas stateless and avoid modifying external state inside stream operations.
10
Your Spring Boot service takes 40 seconds to start in Kubernetes and pods get killed. How do you fix it?
First set a startupProbe so Kubernetes waits for startup before liveness checks begin. Then reduce start time: remove unused starters, enable lazy initialisation where safe, avoid heavy work in @PostConstruct, give enough CPU at start and consider AppCDS. For very fast startup, a GraalVM native image built with Spring AOT can start in under a second, with some trade-offs.
11
A query is fast in development but takes 8 seconds in production. How do you investigate?
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.
12
Write a Kafka producer and consumer in Spring Boot.
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.
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.
14
Write a Java program to check whether a number is prime.
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
You need to remove items from an ArrayList while looping over it. How do you do it safely?
Removing inside a for-each loop throws ConcurrentModificationException. Use list.removeIf(item -> item.isExpired()), which is clear and efficient. Alternatives are an explicit Iterator calling iterator.remove(), or looping backwards by index. For large lists removeIf is best because it shifts elements once instead of on every removal.
16
Read a large text file line by line efficiently and count lines containing ERROR.
Stream the file lazily so it never loads fully into memory.
Path p = Path.of("app.log");
try (Stream<String> lines = Files.lines(p)) {
long errors = lines
.filter(l -> l.contains("ERROR"))
.count();
System.out.println(errors);
}
try-with-resources closes the file handle. BufferedReader.readLine() in a loop is an equally good option.
17
What is the difference between Collectors.toMap() and groupingBy()?
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.
18
An API needs to find the price band for any amount, for example the nearest lower slab. Which structure fits?
TreeMap is ideal because it keeps keys sorted and offers navigation methods. Store slab start amounts as keys and the band as value, then floorEntry(amount) returns the largest slab not above the amount in O(log n). ceilingKey, headMap and tailMap help with similar range queries such as tax slabs or delivery charges.
19
Exceptions are being swallowed with empty catch blocks in your codebase. How would you fix this?
Empty catches hide failures and make production issues invisible. I would find them with static analysis like SonarQube, then decide per case: handle the error properly, rethrow wrapped with context, or at least log with the stack trace. I would add a global exception handler for APIs and a team rule in code review and lint config to block new empty catch blocks.
20
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.
21
Map a one-to-many relation between Order and OrderItem in JPA.
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;
}
22
What is the difference between wait() and sleep()?
wait() is an Object method called inside synchronized code; it releases the monitor and waits until notify(), notifyAll() or a timeout. sleep() is a Thread static method that pauses the current thread for a time but keeps any locks it holds. wait() is for coordination between threads, while sleep() simply delays. Modern code prefers Condition, BlockingQueue or CountDownLatch.
Transient: a new object not yet linked to a persistence context. Managed (persistent): attached to the context, so changes are tracked and flushed automatically through dirty checking. Detached: was managed but the context closed or it was evicted; changes are not tracked until merge(). Removed: scheduled for deletion on flush. persist, merge, detach and remove move entities between these states.
24
Print numbers 1 to 10 alternately from two threads (odd and even).
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).
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.
At startup Spring Boot reads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each class uses conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so it creates beans only when the library is on the classpath and you have not defined your own. Run with --debug to see the condition report showing what was applied and why.
27
Explain the happens-before relationship in the Java Memory Model.
Happens-before is the rule that guarantees one action's effects are visible to another. Examples: unlocking a monitor happens-before a later lock of the same monitor, a volatile write happens-before later reads of it, Thread.start() happens-before actions in the started thread, and actions in a thread happen-before another thread's successful join() on it. Without such an edge, threads may see stale or reordered values.
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.
29
Should a service layer throw checked or unchecked exceptions? Defend your choice.
I prefer unchecked domain exceptions in the service layer. Checked exceptions force every caller to catch or declare them, leak low level details through layers and do not work well with lambdas. Unchecked exceptions with clear names, handled centrally by a controller advice, keep code clean. Spring follows the same idea by translating SQLException into its unchecked DataAccessException family.
30
A counter shared between threads shows wrong totals. How do you fix it?
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.
Count with a map, then keep a min-heap of size K.
Map<String, Integer> cnt = new HashMap<>();
for (String w : words) cnt.merge(w, 1, Integer::sum);
PriorityQueue<String> pq = new PriorityQueue<>(
Comparator.comparingInt(cnt::get));
for (String w : cnt.keySet()) {
pq.offer(w);
if (pq.size() > k) pq.poll();
}
Time O(n log k). Reverse the heap contents for highest first.
32
Tell me about a time a production incident happened because of your code.
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.
33
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.
34
Why is PreparedStatement preferred over Statement?
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.
javac compiles source code into bytecode, not native machine code. Any machine with a compatible JVM can run that same .class file, so the code is written once and run anywhere. The JVM itself is platform specific; there are separate JVM builds for Windows, Linux and macOS, but the bytecode they run is identical.
36
Users get LazyInitializationException when the API returns an entity. What is happening?
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.
Few big employers listed in Chandigarh?
Many Chandigarh candidates also apply to teams in Gurgaon and to remote or hybrid roles. Practise the Gurgaon set as well.
Which companies hire Java professionals in Chandigarh?
Companies with large offices in Chandigarh include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are Java interviews in Chandigarh different from other cities?
The questions depend more on the company than the city. Chandigarh's mix of employers decides the style: Interviews usually check strong fundamentals and practical tool skills
How do I find Java jobs in Chandigarh?
Shortlist companies with Chandigarh offices, keep your CV focused on Java projects, apply on company career pages and job portals with the Chandigarh filter, and practise the questions on this page before each interview.