Java Interview Questions 2026
121 Java interview questions from Amazon, Google, Accenture, Wipro. All difficulty levels, all roles. Upvoted by engineers who were asked them.
Java Questions by Company
Amazon (6)
Given an array of integers and a target sum, return all unique triplets that sum to the target. Discuss time and space complexity. Then extend the problem to k-sum and analyze how recursion depth changes performance for large k.
Design a distributed rate limiter that can handle 10M requests per second across multiple data centers. Discuss consistency tradeoffs, the choice between token bucket vs leaky bucket, and how you would handle clock skew across regions.
Given a directed graph representing service dependencies, detect all strongly connected components and explain how this maps to identifying circular dependencies in a microservices architecture.
Given an array of integers, find the length of the longest subarray with a sum equal to zero. Explain the prefix sum + HashMap approach and why the naive O(n2) solution is unacceptable for large inputs.
Explain Amazon's DynamoDB single-table design pattern. Why do you put multiple entity types in one table? Walk through a real example with access patterns, partition key / sort key design, and GSI usage.
Serialize and deserialize a binary tree. Implement both functions and explain why BFS serialization makes deserialization simpler than DFS. What is the time and space complexity?
Google (3)
Given a binary tree, return the boundary of the tree in anti-clockwise direction starting from the root. The boundary consists of the left boundary, leaves, and the right boundary in reverse.
Implement a topological sort for a directed acyclic graph. Then extend it to detect cycles and explain how this maps to dependency resolution in build systems like Bazel.
Given a list of intervals, merge all overlapping intervals and return the result. Explain the sort-then-scan approach and the edge cases (touching intervals, single interval, all disjoint).
Accenture (12)
What differences do you see between Selenium and Playwright in automation testing? Cover architecture, browser support, speed, built-in waiting mechanisms, and cross-language support.
How can you retrieve all the options available in a dropdown using Selenium? Explain the Select class, how to handle both static and dynamic dropdowns, and edge cases like dropdowns built with div/ul instead of the native select element.
What are the different wait mechanisms in Selenium (Implicit, Explicit, Fluent Wait), and when should each be used? Explain the downsides of Thread.sleep() and how WebDriverWait improves reliability.
How do you handle dynamic elements or changing locators in Selenium automation? Discuss strategies like relative locators, XPath axes, CSS attribute wildcards, and Page Object Model to insulate tests from DOM changes.
What is the purpose of the indexOf() method and how can it be used when removing duplicate characters from a string in Java? Walk through an O(n) solution using a LinkedHashSet or boolean array.
When two developers push changes to the same file in Git simultaneously, how would you resolve the merge conflict? Walk through: pulling latest, identifying conflict markers (<<<, ===, >>>), choosing which changes to keep, testing after resolution, and committing the merge.
How does adding + "" help convert a char value into a String in Java? Explain Java's string concatenation rules, why char + "" produces a String while char + char produces an int, and alternative approaches like String.valueOf(char) or Character.toString(char).
What does @SpringBootApplication actually do? Which three annotations does it combine, and what does each one do?
Design a REST controller in Spring Boot for a "create order" endpoint. What annotations and validation would you use to ensure a malformed request returns 400 instead of crashing?
Explain constructor injection vs field injection (@Autowired on a field) in Spring. Why do most teams now prefer constructor injection?
How do you implement centralized exception handling across all controllers in a Spring Boot application, so you don't repeat try/catch in every endpoint?
What does Spring Boot Actuator give you out of the box for a microservice running in production? Name at least 3 endpoints and what each is used for.
Wipro (16)
Explain the difference between a Scenario and a Scenario Outline in Cucumber BDD. When would you use a Scenario Outline, and how do you supply multiple data rows using the Examples table? Show a real-world login test example.
Describe how pop-ups can be handled using Selenium. Cover alert/confirm/prompt dialogs (driver.switchTo().alert()), browser-native file upload dialogs, and custom modal pop-ups built with HTML/CSS.
What is Fluent Wait in Selenium and when is it used? Compare it with WebDriverWait, explain how to configure polling interval and ignored exceptions, and give a scenario where Fluent Wait is the only viable option.
What is Parallel Testing and why is it useful in automation? Explain how to configure parallel execution in TestNG using the suite XML, the thread-safety concerns with WebDriver instances, and how to manage them with ThreadLocal.
Provide an XPath expression to fetch values from the second column of a web table. Explain absolute vs relative XPath, axes like following-sibling and child, and how to handle tables with dynamic row counts.
Describe the role of a Step Definition file in Cucumber BDD. How does Cucumber link a Gherkin step to a Java method using annotations like @Given, @When, @Then? Show a complete example with a feature file and its corresponding step definition.
How are Tags used to organise or control test execution in Cucumber? Explain how to tag scenarios with @smoke, @regression, @wip, how to run only specific tagged tests from the command line, and how tags can be combined with AND/OR/NOT logic.
Explain the purpose of Data Tables in Cucumber scenarios. How do they differ from Scenario Outline? Show an example where a Data Table passes multiple fields to a single step (e.g., a registration form), and how to read it using DataTable or a list of maps in the step definition.
Explain different ways to perform page scrolling during Selenium automation. Cover: JavascriptExecutor (scrollBy, scrollIntoView), Actions class for keyboard scroll, scrolling to a specific element, and infinite scroll testing strategies.
Explain the purpose of the pom.xml file in a Maven project. Describe the key sections: groupId/artifactId/version, dependencies, plugins, build lifecycle phases (compile, test, package, install), and how to add a Selenium + TestNG dependency with the correct scope.
Describe JSON Schema Validation and its importance in API testing. What is a JSON schema? How do you validate that an API response conforms to the expected schema using Rest Assured or Postman? Give an example schema for a user object with required fields and type constraints.
Write a program to remove duplicate elements from an array and calculate the frequency of each character in a string. For the array: use a LinkedHashSet or a frequency map. For character frequency: use a HashMap<Character, Integer>. Analyse time and space complexity of each approach.
How can nested JSON responses be handled in API testing? Show how to extract a deeply nested value (e.g., response.data.user.address.city) using Rest Assured's JsonPath, and how to validate arrays of objects within the response.
What is an Automation Framework? Explain its structure. Describe the layers: test data, page objects, utilities, test runner, reporters. Why is a framework needed vs raw Selenium scripts? Compare Data-Driven, Keyword-Driven, and Hybrid frameworks.
Describe OOP concepts and how they are applied in automation frameworks. Give concrete examples: Encapsulation in Page Objects (private WebElements), Inheritance for BaseTest/BasePage, Polymorphism for multi-browser driver factories, and Abstraction via interfaces for reporting.
Explain the usage of Java collections in automation frameworks. When would you use a List vs Set vs Map in a test framework? Give real examples: storing test data in a List, deduplicating locators in a Set, mapping test case names to results in a LinkedHashMap.
Infosys (9)
Explain the difference between JDK, JRE, and JVM. How are they related? Describe the JVM internals: class loader, bytecode verifier, interpreter, JIT compiler, garbage collector, and how they work together to run a Java program.
What is the difference between String, StringBuilder, and StringBuffer in Java? When would you use each? Explain immutability, thread safety, performance implications, and give an example where using String in a loop causes excessive object creation.
How do you implement custom validation in Spring Boot? Explain the approach using @Constraint and ConstraintValidator, where to place the annotation, and how to return meaningful error messages through BindingResult.
Explain the Java Memory Model. What are heap and stack? How does garbage collection work? Describe generational GC (Young, Old, Metaspace), GC roots, mark-and-sweep, and how to diagnose memory leaks with tools like VisualVM or jmap.
Design a library management system. Include entities (Book, Member, Loan), relationships, and key operations: borrow, return, search, fine calculation. Discuss how to handle concurrent borrows of the last copy of a book.
What are design patterns? Explain Singleton, Factory, and Observer patterns with Java code examples. In which Spring Boot components are these patterns used internally?
What is the difference between checked and unchecked exceptions in Java? When should you use each? Explain the exception hierarchy and best practices for custom exceptions in a Spring Boot REST API.
Explain REST API best practices. What makes an API RESTful? Cover: proper use of HTTP verbs, status codes, versioning strategies (/v1/users vs Accept header), pagination (cursor vs offset), and HATEOAS.
What is multithreading in Java? Explain synchronised keyword, wait/notify, and the difference between Thread and Runnable. Write a simple producer-consumer implementation using BlockingQueue.
TCS (9)
Explain the difference between HashMap and ConcurrentHashMap in Java. When would you use each? Describe segment locking in Java 7 vs the CAS-based approach in Java 8+, and why you should never use HashMap in a multi-threaded context.
How do you handle transactions in Spring Boot? Explain the @Transactional annotation, propagation levels (REQUIRED, REQUIRES_NEW, NESTED), isolation levels, and how Spring proxies intercept methods — including why self-invocation bypasses the proxy.
Design a REST API for an e-commerce cart system. Define the endpoints (add item, remove item, get cart, checkout), explain authentication with JWT, handle race conditions on inventory, and discuss idempotency for the checkout endpoint.
What is the difference between fail-fast and fail-safe iterators in Java Collections? Give examples of collections that use each, explain the ConcurrentModificationException, and show how to safely remove elements during iteration.
What are the SOLID principles? Explain each with a real-world Java example. Then describe a scenario where rigidly following SOLID leads to over-engineering, and how you balance pragmatism with good design.
Explain the difference between ArrayList and LinkedList in Java. For a TCS banking project, you need to insert records at the front of a list frequently. Which would you choose and why?
Explain Spring Boot auto-configuration. How does @SpringBootApplication work under the hood? What is the difference between @Component, @Service, @Repository, and @Controller in Spring?
Design a library management system with online book reservation. Students can search, reserve, and borrow books. Librarians can manage inventory. Cover the database schema, REST APIs, and how you handle concurrent reservations of the last copy.
Write a Java program to rotate a matrix 90 degrees clockwise in-place. Explain the transpose-then-reverse approach and why it is O(n2) time with O(1) extra space.
Swiggy (5)
Given a list of delivery time windows for N restaurants, find the maximum number of restaurants whose windows overlap at any point in time. Explain the sweep-line approach, time complexity, and how this maps to capacity planning for Swiggy's logistics team.
Implement a rate limiter for Swiggy's API gateway using the token bucket algorithm. Handle 1000 requests/second per user. Code the solution and explain how you'd deploy it across multiple API servers with Redis.
Given delivery time estimates for N restaurants, find the restaurant with the minimum average delivery time across all its orders. Handle ties and explain your data structure choices.
Design the data model for Swiggy's menu system. A restaurant has categories, items, add-ons, variants, and availability windows (breakfast/lunch/dinner). How do you model this in PostgreSQL and handle real-time menu updates?
You need a collection that maintains insertion order AND gives O(1) lookup by key. Which Java collection would you use, and why not a plain HashMap?
Meta (5)
Given Meta's social graph, find all friend-of-friend recommendations for a user that are not already friends. Discuss BFS at scale, how to prune the search space, and how to rank recommendations by mutual friend count efficiently.
Given a social graph, find all users within K hops of a given user. Implement BFS with a visited set. Then discuss how you would scale this to Meta's 3 billion user graph using partitioning.
Given an array of N integers, find the maximum product subarray. Explain why you need to track both the maximum and minimum product ending at each position, and handle zeros and negative numbers.
Given a social graph, find the shortest chain of mutual connections between two users (like LinkedIn's "degrees of connection"), and explain how bidirectional BFS improves performance over a single-direction BFS at this scale.
What is a memory leak in Java despite having a garbage collector? Give a concrete example involving a static collection.
Zomato (2)
Given a list of restaurant ratings and a minimum threshold, return the top-k restaurants sorted by rating using a min-heap. Explain why a heap beats a full sort for large k, and the time complexity of both approaches.
How does Zomato calculate a restaurant's "delivery fee"? The fee depends on distance, demand, time of day, and partner availability. Implement a pricing function given these inputs and discuss fairness trade-offs.
Adobe (2)
Explain the difference between raster and vector image formats. How does Adobe Photoshop store a PSD file differently from Illustrator's AI format? Discuss lossy vs lossless compression and when you would choose PNG vs JPEG vs WebP.
Implement a basic version of Adobe Lightroom's non-destructive editing model. All edits (brightness, contrast, crop) are stored as a list of operations, not applied to the original image. Explain the data structure and how you apply/undo operations.
Microsoft (5)
Given a binary tree, print nodes level by level (BFS traversal). Then modify it to print alternate levels in reverse order (zigzag traversal). Analyse time and space complexity.
Given a 2D grid of 0s and 1s, count the number of islands. Then extend: find the largest island, and then explain how you would solve this for a streaming grid that changes in real time using a Union-Find structure.
Find all pairs in an array that sum to a given target value. Explain the HashSet approach for O(n) time, handle duplicate pairs correctly, and discuss edge cases (negative numbers, empty array).
Design a data structure that supports insert, delete, and getRandom in O(1) average time. Walk through your approach.
Rewrite this imperative loop using Java Streams: filter a list of orders for status "PAID", then sum their amounts. Explain one case where a stream would actually perform worse than the loop.
Flipkart (5)
Implement a LRU (Least Recently Used) cache with O(1) get and put operations. Explain the HashMap + doubly linked list approach and why a simple array or single HashMap is insufficient.
Design a coupon/discount system for Flipkart Big Billion Days. The system must validate, apply, and prevent double-use of millions of coupons with high concurrency. Cover idempotency and distributed locking.
Given a directed graph representing category hierarchies in an e-commerce catalog, find the shortest path between two categories. Explain BFS vs Dijkstra for unweighted vs weighted graphs.
Design Flipkart's order management system. From "Place Order" to "Delivered", walk through every state transition, the microservices involved, how you handle partial failures (payment succeeds but inventory deduct fails), and eventual consistency.
What is a race condition in Java, and how does synchronized prevent it? Show a minimal example of a non-thread-safe counter and the fix.
Apple (1)
Given a BST, find the closest value to a given target. Explain the O(log n) iterative approach using BST properties, and how the answer changes if the tree is unbalanced.
Netflix (2)
Given a list of movie ratings (1-5 stars) for N users, compute the Pearson correlation between two users to measure taste similarity. Explain how this feeds into collaborative filtering.
What is the circuit breaker pattern? Explain the three states (Closed, Open, Half-Open), when to trip and reset the breaker, and how Netflix's Hystrix library implements it. When would you NOT use a circuit breaker?
Uber (2)
Given a city map as a weighted graph, find the shortest travel time from a driver's current location to all potential passenger pickup points simultaneously. How does Dijkstra's multi-source variant solve this?
Given a list of GPS coordinates representing a driver's path, compute the total distance travelled. Then find the longest contiguous segment where the driver was stationary (speed < 5 km/h). Discuss floating-point precision issues.
Airbnb (1)
Given a list of bookings with start and end dates, find the minimum number of rooms needed so that no two overlapping bookings share a room. Explain the sweep-line and min-heap approaches.
Stripe (1)
Explain the difference between synchronous and asynchronous API design using Stripe as an example. When does a charge complete immediately vs require a webhook? How do you handle the intermediate "pending" state in your database?
Razorpay (2)
Explain the UPI payment flow end-to-end: from user entering a VPA to money credited. What is NPCI's role? What happens when the beneficiary bank is down? How does Razorpay handle UPI collect vs UPI intent flows?
How do you implement a distributed ledger for financial transactions? Explain double-entry bookkeeping in code, why you never update a balance directly, and how you use event sourcing to reconstruct the current balance from a transaction log.
PhonePe (2)
Explain how PhonePe handles transaction deduplication. A user taps "Pay" twice due to network lag. The same debit must not happen twice. Walk through idempotency at the API level, database level, and bank integration level.
What is eventual consistency and why is it acceptable for some PhonePe features but not others? Give examples: where strong consistency is mandatory (debit/credit) vs where eventual consistency is fine (notification delivery, analytics).
Paytm (1)
How does Paytm's QR code payment work technically? Explain the difference between static QR (merchant VPA encoded) and dynamic QR (amount pre-filled). What are the security implications of each?
Salesforce (5)
Design Salesforce's governor limits enforcement system. Every Apex code execution is limited (SOQL queries, CPU time, heap). How do you track and enforce these limits in real time across millions of concurrent org executions?
Explain Salesforce's metadata-driven architecture. Why does storing field definitions as data (instead of schema changes) enable the multi-tenant model? What are the trade-offs in query performance?
What is Salesforce's SOQL and how does it differ from SQL? Explain relationship queries (parent-to-child and child-to-parent), the 100-SOQL governor limit, and how you optimise queries to avoid hitting it.
Design Salesforce Flow (visual process automation). Users define business workflows (if-then rules, send emails, create records) in a UI. How do you store, version, execute, and debug millions of active flows in a multi-tenant environment?
When would you use the Builder pattern in Java instead of a constructor with many parameters? Sketch a builder for a User class with 6 optional fields.
Oracle (5)
Explain Oracle's redo log and undo log. How do they work together to provide crash recovery and read consistency? Walk through what happens when a transaction commits, then the server crashes, then restarts.
Design Oracle Cloud's IAM (Identity and Access Management) system. Thousands of customers, each with their own users, groups, and policies. How do you evaluate a permission check in under 10ms for every API call?
Explain Oracle RAC (Real Application Clusters). How do multiple nodes access the same database storage? What is the Cache Fusion protocol? When would you choose RAC over a primary-replica setup?
Explain the difference between the young generation and old generation in JVM garbage collection. Why do most GC pauses come from minor (young-gen) collections rather than major ones, and when does that assumption break down?
Why must you override hashCode() whenever you override equals() in Java? What breaks if you only override equals()?
LinkedIn (3)
How does LinkedIn's "Who viewed your profile" feature work? What data is stored, how long is it retained, and how do you provide the feature to free users (last 5 viewers) vs Premium (full list) without exposing premium-only data?
LinkedIn uses Kafka extensively. Explain how you would design the Kafka topic structure for LinkedIn's activity events (profile view, connection request, message sent). Cover: topic naming, partitioning strategy, consumer group design, and exactly-once semantics.
Explain the difference between synchronized, ReentrantLock, and ConcurrentHashMap for protecting shared state in Java. When would you choose each?
Atlassian (2)
Explain how Jira's JQL (Jira Query Language) parser works. Walk through lexing, parsing, and AST generation. How do you translate a JQL query like "assignee = currentUser() AND status = Done" into an efficient SQL query?
Given a list of Jira sprint start/end dates, find all sprints that overlap with a given date range. Implement an efficient solution using interval trees or sorted arrays with binary search.
Capgemini (2)
What is the Page Object Model (POM) design pattern in Selenium? Why is it used? Show the structure of a POM class for a login page and explain how it improves test maintainability.
What is test reporting in automation? How do you generate Allure reports in a Playwright/TestNG framework? What information should a good test report contain and how do you integrate it with your CI/CD pipeline?
PayU (5)
Given an array of transaction amounts, find all pairs whose sum equals a given target. Return the count of unique pairs. For example: [100, 200, 300, 400], target = 500 → pairs: (100,400), (200,300) → count: 2. What is the time and space complexity of your approach?
You have an array of daily payment failure counts for the past 30 days. Find the longest contiguous subarray where failures stayed below a given threshold k. Explain your sliding window approach and walk through the algorithm step by step.
Given a list of payment events, each with a merchant ID and an amount, use a HashMap to return the top 3 merchants by total transaction volume. How would you handle ties? Write the complete solution.
Given a 2D matrix representing a payment heatmap (rows = hours, columns = days), find the submatrix with the maximum sum. The submatrix represents the peak payment activity window. Describe your approach — can you do better than O(n³)?
What is the difference between a checked and an unchecked exception in Java? Why do many teams avoid checked exceptions for business logic errors?
LTIMindtree (6)
How would you process and track real-time data in GCP?
How would you integrate Google Cloud Pub/Sub into a Java application?
Explain the architecture of your Java application on GCP.
Write a Java application that publishes a message to Google Cloud Pub/Sub when a new payment is processed.
Which design patterns would you choose while designing an event-driven architecture on GCP?
Create an Apache Beam pipeline that reads a text file from Google Cloud Storage (GCS), converts all text to uppercase, and writes the output back to GCS.
Deloitte (1)
Explain the difference between an abstract class and an interface in Java. With default methods now allowed in interfaces since Java 8, when would you still choose an abstract class?
Grab (1)
Given an array of ride fare amounts collected over a day, find the maximum sum of any contiguous subarray of exactly k rides (a sliding window problem). Walk through the O(n) approach.
Practice these questions with AI feedback
Get instant grading on your answers, identify your weak areas, and generate a personalised 14-day study plan — all free.
Build my study plan →