Skip to content

Goldman Sachs Java Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

About Goldman Sachs hiring for Java roles

Goldman Sachs is a global investment banking, securities and asset management firm. Its Bengaluru and Hyderabad offices are major engineering and operations centres supporting trading, risk, compliance and consumer platforms. It hires in India for software engineers, quality engineers, data engineers, quantitative strategists and risk or operations analysts.

For Java roles, this Goldman Sachs practice set focuses most on Java 8+ Features and Streams (7), Multithreading and Concurrency (5), OOP in Java (5), JDBC, Hibernate and JPA (4). It has 6 easy, 21 medium, 3 hard questions, so you can start easy and work up to the harder ones.

Company type
Banking & finance
Headquarters
New York, USA
Main India offices
Bengaluru, Hyderabad, Mumbai

Goldman Sachs Java interview process

  1. Online assessment (coding + quant + aptitude)
  2. Technical round 1 (DSA)
  3. Technical round 2 (design or CS fundamentals)
  4. Hiring manager round
  5. HR or culture round

Typical pattern based on public candidate experiences. Rounds vary by role, team and year.

Solved for Goldman SachsStart 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 the difference between intermediate and terminal operations in streams?

Save to ▾
Show answer
Intermediate operations like filter, map, sorted and distinct return a new stream and are lazy; nothing runs until a terminal operation is called. Terminal operations like collect, forEach, reduce, count and findFirst trigger processing and produce a result. Laziness lets streams fuse steps into a single pass and short-circuit, so findFirst on filtered data stops early.
02

Map a one-to-many relation between Order and OrderItem in JPA.

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

Users get LazyInitializationException when the API returns an entity. What is happening?

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

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

What is the difference between throw and throws?

Save to ▾
Show answer
throw is a statement used inside a method to actually raise an exception object, for example throw new IllegalStateException("closed"). throws is used in a method signature to declare which checked exceptions the method may pass to its caller, for example void read() throws IOException. A method can declare many exceptions with throws but throws one object at a time.
06

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

What is the difference between map() and flatMap()?

Save to ▾
Show answer
map() transforms each element into exactly one new element, so a Stream of orders mapped to totals stays one-to-one. flatMap() transforms each element into a stream and flattens all of them into one stream, which is useful for one-to-many cases, such as turning a list of orders into a single stream of all items with orders.stream().flatMap(o -> o.items().stream()).
08

What is the difference between Collectors.toMap() and groupingBy()?

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

Why must you be careful when initial capacity of a HashMap is too small?

Save to ▾
Show answer
If a HashMap starts small and grows large, it resizes many times; each resize allocates a new array and rehashes every entry, which costs CPU and creates garbage. When the expected size is known, use HashMap.newHashMap(n) in Java 19 or later, or set capacity to n divided by 0.75. Too large a capacity wastes memory, so size it to real data.
10

What does the volatile keyword guarantee?

Save to ▾
Show answer
volatile guarantees visibility and ordering: a write to a volatile field is immediately visible to other threads, and it prevents reordering around that access under the Java Memory Model. It does not make compound operations like count++ atomic, because that is a read, modify and write. Use it for flags such as a stop signal, and use AtomicInteger or locks for counters.
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

An API listing 100 orders fires 101 SQL queries. How do you fix it?

Save to ▾
Show answer
This is the N+1 problem from a lazy association loaded in a loop or by JSON serialisation. Fetch what the endpoint needs in one query with JOIN FETCH or @EntityGraph(attributePaths = "items"), or use a DTO projection query. For collections with pagination, fetch ids first, then fetch associations in a second query to avoid in-memory paging. Add a test that asserts the query count.
13

Is it good practice to catch Exception or Throwable?

Save to ▾
Show answer
Usually no. Catching Throwable also catches Errors like OutOfMemoryError that the app cannot recover from, and catching Exception hides bugs by treating all failures the same. Catch the most specific exceptions you can handle. A broad catch is acceptable only at a top boundary, such as a global handler or thread entry point, where you log and return a safe error.
14

Explain the SOLID principles briefly.

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

Legacy code uses anonymous classes and loops everywhere. How would you modernise it safely?

Save to ▾
Show answer
First add tests around the behaviour. Then refactor in small steps: anonymous Comparators and Runnables become lambdas, simple loops that filter and transform become streams, and null checks around returns become Optional where useful. Keep complex loops with early exits as loops if a stream is less readable. Use IDE refactorings and review each change to avoid altering behaviour.
16

Write a custom unchecked exception and a Spring handler that returns HTTP 404.

Save to ▾
Show answer
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()); } }
17

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

A stream pipeline that updates a shared ArrayList in forEach gives random results with parallel(). Why?

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

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

What is the N+1 select problem in Hibernate and how do you fix it?

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

Tell me about a time you improved performance by choosing a better data structure.

Save to ▾
Show answer
Situation: a report job matching 2 lakh transactions to customers took 40 minutes. Task: bring it under the 5 minute window. Action: profiling showed list.contains() inside a loop, which was O(n squared). I loaded customer ids into a HashSet and grouped transactions with a HashMap. Result: runtime dropped to 50 seconds and I shared the pattern in our team wiki.
22

What is the difference between method overloading and method overriding?

Save to ▾
Show answer
Overloading means several methods in the same class share a name but differ in parameter list; it is resolved at compile time. Overriding means a subclass provides its own version of a parent method with the same signature; it is resolved at runtime through dynamic dispatch. Return type alone cannot overload a method, while overriding allows a covariant return type.
23

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

How do you prepare for coding rounds as a Java developer?

Save to ▾
Show answer
Situation: I was preparing for product company interviews while working. Task: get strong at DSA in limited time. Action: I solved two problems a day by pattern, such as sliding window and graphs, always in Java with Collections, timed myself and reviewed mistakes every weekend. Result: in three months I solved 250 problems, cleared online tests comfortably and could explain time complexity clearly.
25

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

Tell me about a time you made a codebase more readable.

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

How do you take a thread dump and a heap dump of a running Java process?

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

Why does Java not support multiple inheritance of classes?

Save to ▾
Show answer
Multiple inheritance of classes creates the diamond problem: if two parents have the same method with different code, the child cannot know which one to use, and state duplication becomes messy. Java avoids this by allowing one superclass but many interfaces. If two interfaces provide the same default method, the class must override it and can call a specific one with InterfaceName.super.method().
29

Objects used as HashMap keys cannot be found after insertion. What could be wrong?

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

Tell me about a time you solved a concurrency bug.

Save to ▾
Show answer
Situation: our wallet service sometimes showed wrong balances under load. Task: find the race and fix it without slowing the API. Action: I reproduced it with a JMeter test, found a read-then-update pattern in two concurrent requests, and replaced it with an atomic SQL update plus optimistic locking with a version column. Result: zero balance mismatches across festival traffic and a reusable load test for future changes.

Tips to crack the Goldman Sachs Java interview

  • Practise probability and quantitative aptitude questions, which commonly appear in Goldman Sachs online assessments.
  • Learn basic financial concepts such as equities, bonds, derivatives and risk, especially for strats and data roles.
  • Prepare clear stories about teamwork and integrity, as Goldman Sachs emphasises its business principles and client focus.
  • 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; Goldman Sachs interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Goldman Sachs Java interview?

Candidates usually go through 5 stages: Online assessment (coding + quant + aptitude); Technical round 1 (DSA); Technical round 2 (design or CS fundamentals); Hiring manager round; HR or culture 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 Goldman Sachs Java interview?

This practice set leans on Java 8+ Features and Streams (7), Multithreading and Concurrency (5), OOP in Java (5), JDBC, Hibernate and JPA (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Goldman Sachs interviewers ask you to walk through real work.

Are these the exact questions asked at Goldman Sachs?

No. These are curated practice questions that match the skills and difficulty usually tested in banking & finance interviews like Goldman Sachs's. They are not a leaked or verified list of past questions.

Where does Goldman Sachs hire Java professionals in India?

Goldman Sachs has large teams in Bengaluru, Hyderabad, Mumbai. Openings and locations change often, so check the Goldman Sachs careers page and filter by city and experience.

Java questions for similar companies