Skip to content

Java Interview Questions in Gurgaon

36 practice questions with answers for Java interviews in Gurgaon.

Java jobs in Gurgaon

Gurgaon (Gurugram) is home to many multinational, consulting, fintech and consumer-internet offices. Interviews often expect strong business understanding along with technical skills, especially for analytics and product-facing roles.

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

Solved for GurgaonStart 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 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.
02

What are the primitive data types in Java and their sizes?

Save to ▾
Show answer
Java has eight primitives: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2 bytes, UTF-16 code unit) and boolean (true or false, size JVM dependent). Primitives store values directly and have default values when used as fields, for example 0 for int and false for boolean. Each has a wrapper class such as Integer.
03

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

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

Explain the entity lifecycle states in JPA.

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

You need to add a new payment method to a system that has a big if-else on payment type. How would you redesign it?

Save to ▾
Show answer
This breaks the Open/Closed principle. I would create a PaymentProcessor interface with a pay() method and one implementation per type, such as UpiProcessor and CardProcessor. A factory or a Spring map of beans keyed by type picks the right one. Adding a new method then means adding one new class without touching existing tested code, and each processor can be unit tested alone.
07

Write Java code to reverse an integer without converting it to a string.

Save to ▾
Show answer
Take the last digit with % 10 and build the result, checking for overflow. public static int reverse(int x) { long rev = 0; while (x != 0) { rev = rev * 10 + x % 10; x /= 10; } if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; return (int) rev; } Negative numbers work because % keeps the sign in Java.
08

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

Bind typed configuration properties with validation in Spring Boot.

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

You need a cache that evicts the least recently used item when full. How would you build it in Java?

Save to ▾
Show answer
Extend LinkedHashMap with accessOrder set to true and override removeEldestEntry to return true when size exceeds capacity. Each get moves the entry to the end, so the eldest is the least recently used. It is not thread safe, so wrap it with synchronization for shared use. In production prefer Caffeine, which offers size and time based eviction with high concurrency.
11

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

Implement a producer-consumer using BlockingQueue.

Save to ▾
Show answer
BlockingQueue handles waiting and signalling for you. BlockingQueue<Integer> q = new ArrayBlockingQueue<>(10); Runnable producer = () -> { for (int i = 0; i < 100; i++) { try { q.put(i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } }; Runnable consumer = () -> { try { while (true) System.out.println(q.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; put blocks when full and take blocks when empty.
13

When would you choose ArrayDeque over Stack and LinkedList?

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

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

What is the difference between checked and unchecked exceptions?

Save to ▾
Show answer
Checked exceptions extend Exception (but not RuntimeException) and must be caught or declared with throws, for example IOException and SQLException. Unchecked exceptions extend RuntimeException, such as NullPointerException and IllegalArgumentException, and need no declaration. Use checked exceptions for recoverable conditions callers must handle and unchecked ones for programming errors. Errors like OutOfMemoryError should not be caught.
16

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).
17

What are virtual threads and when should you use them?

Save to ▾
Show answer
Virtual threads, final in Java 21, are lightweight threads managed by the JVM and mounted on a small pool of carrier OS threads. When one blocks on I/O, it unmounts so the carrier can run another. You can run millions of them, which suits thread-per-request servers doing lots of blocking calls. They do not speed up CPU-bound work, and you should not pool them.
18

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

What is the difference between JPA, Hibernate and Spring Data JPA?

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

A team member chains Optional.get() everywhere and gets NoSuchElementException. What do you suggest?

Save to ▾
Show answer
get() on an empty Optional throws, so it brings back the same problem Optional was meant to solve. Suggest orElseThrow with a clear domain exception, orElse or orElseGet for defaults, and map or flatMap to chain safe transformations. Static analysis can flag get() without isPresent. Since Java 10 orElseThrow() without arguments is the clear name for the unchecked version.
21

What are text blocks in Java?

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

What is the first level and second level cache in Hibernate?

Save to ▾
Show answer
The first level cache is the persistence context itself; it is per session or EntityManager, always on, and returns the same object for repeated finds by id in one transaction. The second level cache is shared across sessions and optional, backed by providers like Ehcache or Infinispan through JCache. Use it for read-mostly reference data, and be careful about stale data in clustered setups.
23

What is constructor chaining?

Save to ▾
Show answer
Constructor chaining is calling one constructor from another. this(...) calls another constructor in the same class and super(...) calls a parent class constructor; either must be the first statement. If you write neither, the compiler inserts super() automatically. Chaining avoids duplicate initialisation code, for example a no-arg constructor calling this("default", 0).
24

What is exception chaining?

Save to ▾
Show answer
Exception chaining wraps a low level exception in a higher level one while keeping the original as the cause, for example throw new OrderException("save failed", sqlEx). The full stack trace shows both, with Caused by lines. It lets each layer speak its own language without losing the root cause, which is essential when debugging production logs.
25

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

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

What are method references? Give the four types.

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

What does effectively final mean for lambdas?

Save to ▾
Show answer
A lambda can use a local variable from the enclosing method only if that variable is final or effectively final, meaning it is never reassigned after initialisation. Lambdas capture the value, not the variable, so this avoids confusing behaviour and races. To accumulate results, use a stream collector or an AtomicInteger instead of changing a captured local.
29

You have to process tasks in order of priority. Which collection do you use?

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

How do you make sure database changes are released safely?

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

Your Spring Boot service takes 40 seconds to start in Kubernetes and pods get killed. How do you fix it?

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

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

What is CompletableFuture and how is it better than Future?

Save to ▾
Show answer
Future only lets you block with get() to obtain a result. CompletableFuture supports non-blocking composition: thenApply to transform, thenCompose to chain async calls, thenCombine or allOf to join several, and exceptionally or handle for errors. It runs on the common ForkJoinPool by default, but pass your own executor for blocking I/O to avoid starving the pool.
34

Compare String, StringBuilder and StringBuffer.

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

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

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.

Companies with offices in Gurgaon (3)

Frequently asked questions

Which companies hire Java professionals in Gurgaon?

Companies with large offices in Gurgaon include Accenture, Amazon, SAP. Use their company pages below to practise employer-specific sets.

Are Java interviews in Gurgaon different from other cities?

The questions depend more on the company than the city. Gurgaon's mix of employers decides the style: Interviews often expect strong business understanding along with technical skills, especially for analytics and product-facing roles

How do I find Java jobs in Gurgaon?

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