36 practice questions with answers for Java interviews in Jaipur.
Java jobs in Jaipur
Jaipur has a growing IT and IT-enabled services market, with delivery centres, SaaS start-ups and back-office analytics teams around Sitapura and Mahindra World City. Many candidates here also apply to remote and hybrid roles with Delhi NCR teams.
Below are 36 questions that match the mix of service, product and domain employers hiring java developers in Jaipur.
Solved for JaipurStart 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.
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.
02
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.
Autoboxing is automatic conversion between a primitive and its wrapper, such as int to Integer, and unboxing is the reverse. A common pitfall is a NullPointerException when unboxing a null Integer. Another is comparing Integer objects with ==, which works only for cached values from -128 to 127. Boxing inside tight loops also creates extra garbage and slows code.
04
You have to process tasks in order of priority. Which collection do you use?
Use PriorityQueue, a binary heap where poll() always returns the smallest element by natural order or by a Comparator, such as Comparator.comparingInt(Task::priority). Insert and poll are O(log n) and peek is O(1). For multiple threads use PriorityBlockingQueue. Iterating a PriorityQueue does not give sorted order; only repeated poll() does.
05
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.
06
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.
07
What is the difference between HashMap and ConcurrentHashMap?
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.
08
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).
09
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.
10
Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?
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.
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.
13
A getter returns an internal List and callers modify it, causing bugs. How do you fix this?
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.
14
What is the difference between @Component, @Service, @Repository and @Controller?
All four mark a class as a Spring bean for component scanning. @Service and @Component are functionally the same, with @Service showing business logic intent. @Repository also enables translation of persistence exceptions into Spring DataAccessException. @Controller handles web requests and returns views, and @RestController adds @ResponseBody so return values are written as JSON.
15
What is optimistic versus pessimistic locking in JPA?
Optimistic locking adds a @Version column; on update Hibernate checks the version and throws OptimisticLockException if another transaction changed the row, so you retry. It suits low contention. Pessimistic locking uses SELECT FOR UPDATE through LockModeType.PESSIMISTIC_WRITE, blocking others until commit; it suits high contention on the same rows, like seat booking, but can reduce throughput.
16
How do you take a thread dump and a heap dump of a running Java process?
Find the process id with jps or ps, then use jcmd, which is the recommended tool.
jps -l
jcmd <pid> Thread.print > threads.txt
jcmd <pid> GC.heap_dump /tmp/heap.hprof
Older tools jstack and jmap do the same. Take three thread dumps a few seconds apart to spot stuck threads, and analyse heap dumps in Eclipse MAT.
17
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.
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.
19
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.
20
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.
21
Why should we hire you as a Java backend developer?
Situation: in my current role I build Spring Boot services for a payments product. Task: show impact beyond writing code. Action: I improved API latency by 60 percent through query tuning and caching, raised test coverage from 40 to 80 percent and handled on-call calmly. Result: I bring solid Java, Spring and SQL skills, ownership of production and a habit of measuring results, which fits this role.
22
A @Transactional method is not rolling back after an exception. What could be wrong?
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
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.
25
Write a Spring Data JPA repository method that fetches orders with items to avoid N+1.
Use JOIN FETCH or an entity graph.
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("select distinct o from Order o join fetch o.items where o.customerId = :cid")
List<Order> findWithItems(@Param("cid") Long customerId);
@EntityGraph(attributePaths = "items")
List<Order> findByStatus(String status);
}
Both load orders and items in one query.
26
Implement a producer-consumer using BlockingQueue.
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.
28
Users report the app is slow for the first few minutes after every deployment. Why might this happen?
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.
29
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.
30
What is the N+1 select problem in Hibernate and how do you fix it?
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.
Text blocks, final in Java 15, are multi-line string literals written between triple double quotes. They keep line breaks, remove common leading indentation and need far fewer escape characters, which makes embedded JSON, SQL and HTML readable. Methods like formatted() can insert values. They are still normal String objects in the pool.
32
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.
33
You must expose configuration that differs between dev, QA and production. How do you manage it?
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.
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.
35
What are records in Java and when should you use them?
Records, final in Java 16, are concise classes for immutable data. record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors, equals(), hashCode() and toString(). You can add validation in a compact constructor and add methods. Use them for DTOs, API responses and map keys. They cannot extend another class and are not suited to JPA entities, which need mutability.
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.
Few big employers listed in Jaipur?
Many Jaipur candidates also apply to teams in Delhi and to remote or hybrid roles. Practise the Delhi set as well.
Which companies hire Java professionals in Jaipur?
Companies with large offices in Jaipur include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are Java interviews in Jaipur different from other cities?
The questions depend more on the company than the city. Jaipur's mix of employers decides the style: Many candidates here also apply to remote and hybrid roles with Delhi NCR teams
How do I find Java jobs in Jaipur?
Shortlist companies with Jaipur offices, keep your CV focused on Java projects, apply on company career pages and job portals with the Jaipur filter, and practise the questions on this page before each interview.