Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.
About Oracle hiring for Java roles
Oracle develops database software, cloud infrastructure (OCI), enterprise applications such as Fusion ERP and NetSuite, and industry software for banking and healthcare. India hosts major Oracle development and support centres, including Oracle Financial Services Software. It hires for software developers, QA engineers, database engineers, cloud support and data analytics roles.
For Java roles, this Oracle practice set focuses most on Collections Framework (5), Spring Boot and Microservices (5), Multithreading and Concurrency (5), Java Basics and JVM (5). It has 2 easy, 18 medium, 10 hard questions, so you can start easy and work up to the harder ones.
Company type
Product
Headquarters
Austin, Texas, USA
Main India offices
Bengaluru, Hyderabad, Noida, Mumbai, Pune
Oracle Java interview process
Online assessment (aptitude + coding + CS MCQs)
Technical round 1
Technical round 2
Managerial round
HR round
Typical pattern based on public candidate experiences. Rounds vary by role, team and year.
Solved for OracleStart 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.
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.
02
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.
03
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.
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.
05
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.
06
You need a cache that evicts the least recently used item when full. How would you build it in Java?
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.
07
How would you split a monolith into microservices?
Do not split everything at once. Identify bounded contexts with the business, such as orders, payments and catalogue, and pick a module with clear boundaries and high change rate first. Use the strangler fig pattern: route its traffic through a gateway to the new service, give it its own database and sync data through events. Add observability and CI/CD before scaling out further.
08
Group a list of orders by city and sum the amount per city.
Use groupingBy with a summing collector.
Map<String, Double> totals = orders.stream()
.collect(Collectors.groupingBy(
Order::city,
TreeMap::new,
Collectors.summingDouble(Order::amount)));
TreeMap keeps cities sorted. For money, store amounts as long paise or BigDecimal and use Collectors.reducing with BigDecimal::add.
09
What are the key patterns used in microservices built with Spring Boot?
Common patterns are API gateway (Spring Cloud Gateway) for routing and auth, service discovery or Kubernetes services, externalised config, circuit breaker and retry with Resilience4j, database per service, event-driven communication with Kafka, saga for distributed transactions, and observability with Micrometer, tracing and centralised logs. Each service owns its data and deploys independently.
10
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.
11
How do you handle disagreement with a reviewer about your code?
Situation: a senior reviewer asked me to replace my checked exceptions with unchecked ones. Task: decide the right approach without conflict. Action: I asked for the reasons, read our codebase conventions and wrote a small comparison, then agreed because unchecked exceptions fit our global handler. Result: the change merged the same day and I learned to check team conventions before designing error handling.
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.
13
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.
14
A downstream payment service is slow and your API threads pile up. How do you protect your service?
Set strict connect and read timeouts on the HTTP client. Add a Resilience4j circuit breaker so calls fail fast once the error rate crosses a threshold, a bulkhead to limit concurrent calls and retry with backoff only for safe idempotent requests. Return a clear fallback such as payment pending. Monitor breaker state through Actuator metrics and alerts.
15
A deep inheritance hierarchy of six levels is hard to change. How would you refactor it?
I would identify which behaviours actually vary and pull them into small interfaces, then replace inheritance with composition where a class holds strategy objects. Shared helper code can move to separate components. I would refactor step by step behind existing tests, starting from the leaves, so behaviour stays the same. The result is flatter classes that are easier to test and extend.
Try-with-resources, from Java 7, automatically closes any object that implements AutoCloseable when the try block ends, even if an exception is thrown. Resources close in reverse order of opening. If both the body and close() throw, the close exception is added as a suppressed exception. It replaces long finally blocks for files, JDBC connections and streams.
17
Two users booking the last seat both succeed. How do you prevent double booking?
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.
18
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.
19
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.
20
Production shows Connection is not available, request timed out after 30000ms from HikariCP. What do you check?
The pool is exhausted. Check for connection leaks, where code holds connections without closing, by setting leakDetectionThreshold. Look for long transactions doing remote calls inside @Transactional, slow queries holding connections and a pool size too small for the thread count. Fix leaks, move external calls outside transactions, optimise slow queries and then size the pool from load tests.
21
Your service throws OutOfMemoryError: Java heap space in production. How do you investigate?
First capture evidence: enable -XX:+HeapDumpOnOutOfMemoryError and check GC logs to see if heap grows steadily, which signals a leak, or spikes, which signals a large request. Analyse the heap dump in Eclipse MAT or VisualVM and look at the dominator tree for big retainers like static maps or caches. Fix the leak or bound the cache, then increase -Xmx only if the real workload needs it.
22
Objects used as HashMap keys cannot be found after insertion. What could be wrong?
Most likely the class overrides equals() but not hashCode(), or neither, so equal keys land in different buckets. Another cause is a mutable key: a field used in hashCode() was changed after insertion, so the lookup goes to a different bucket. The fix is to implement both methods on the same fields and use immutable keys such as String, records or final classes.
23
Run two tasks in parallel with CompletableFuture and combine their results.
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.
25
An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?
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
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.
27
Write a custom unchecked exception and a Spring handler that returns HTTP 404.
Define the exception, then map it centrally.
public class NotFoundException extends RuntimeException {
public NotFoundException(String msg) { super(msg); }
}
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(NotFoundException.class)
public ProblemDetail notFound(NotFoundException e) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, e.getMessage());
}
}
28
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.
29
GC pauses of two seconds are causing request timeouts. How would you reduce them?
Turn on GC logging with -Xlog:gc* and confirm which collections cause the pauses. Reduce allocation rate by fixing heavy object creation in hot paths. Size the heap correctly and set -Xms equal to -Xmx to avoid resizing. Tune G1 with MaxGCPauseMillis or move to ZGC for sub-millisecond pauses on large heaps. Retest under load before rolling out.
30
What are virtual threads and when should you use them?
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.
Tips to crack the Oracle Java interview
Revise SQL and PL/SQL deeply, including joins, indexes, transactions and query optimisation, as databases are central to Oracle.
Read basic OCI concepts like compute, storage and autonomous database if you are interviewing for cloud teams.
Practise explaining DBMS, operating systems and networking fundamentals, which are often tested in Oracle technical rounds.
Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
Practise the hard questions on this page aloud; Oracle interviewers usually ask follow-ups on your first answer.
Frequently asked questions
How many rounds are there in the Oracle Java interview?
Candidates usually go through 5 stages: Online assessment (aptitude + coding + CS MCQs); Technical round 1; Technical round 2; Managerial round; HR round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.
Which topics should I prepare for the Oracle Java interview?
This practice set leans on Collections Framework (5), Spring Boot and Microservices (5), Multithreading and Concurrency (5), Java Basics and JVM (5). Revise those first, then practise explaining one or two of your own projects end to end, because most Oracle interviewers ask you to walk through real work.
Are these the exact questions asked at Oracle?
No. These are curated practice questions that match the skills and difficulty usually tested in product interviews like Oracle's. They are not a leaked or verified list of past questions.
Where does Oracle hire Java professionals in India?
Oracle has large teams in Bengaluru, Hyderabad, Noida, Mumbai, Pune. Openings and locations change often, so check the Oracle careers page and filter by city and experience.