Skip to content

Java Interview Questions in Bangalore

36 practice questions with answers for Java interviews in Bangalore.

Java jobs in Bangalore

Bangalore (Bengaluru) is India's largest technology hub, with global product companies, engineering centres, unicorn start-ups and big IT-services campuses. Product-company interviews here are usually deeper, with more scenario, design and hands-on rounds.

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

Solved for BangaloreStart 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

Write a unit test for a service class using JUnit 5 and Mockito.

Save to ▾
Show answer
Mock the repository and verify behaviour. @ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock ProductRepository repo; @InjectMocks ProductService service; @Test void throwsWhenMissing() { when(repo.findById(1L)).thenReturn(Optional.empty()); assertThrows(NotFoundException.class, () -> service.get(1L)); verify(repo).findById(1L); } } No Spring context starts, so the test runs in milliseconds.
02

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

What are records in Java and when should you use them?

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

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

Explain the happens-before relationship in the Java Memory Model.

Save to ▾
Show answer
Happens-before is the rule that guarantees one action's effects are visible to another. Examples: unlocking a monitor happens-before a later lock of the same monitor, a volatile write happens-before later reads of it, Thread.start() happens-before actions in the started thread, and actions in a thread happen-before another thread's successful join() on it. Without such an edge, threads may see stale or reordered values.
06

Describe a time you improved the design of existing code.

Save to ▾
Show answer
Situation: our notification module used a 400 line class with switch cases for email, SMS and WhatsApp. Task: add push notifications without breaking anything. Action: I wrote tests for current behaviour, extracted a Notifier interface with one class per channel and used Spring to inject them by type. Result: push was added in one new class, bugs in that module dropped and new channels now take hours, not days.
07

Explain the hierarchy of the Java Collections Framework.

Save to ▾
Show answer
The root interface is Iterable, then Collection, which has List (ordered, allows duplicates: ArrayList, LinkedList), Set (unique: HashSet, LinkedHashSet, TreeSet) and Queue/Deque (PriorityQueue, ArrayDeque). Map is separate and stores key-value pairs: HashMap, LinkedHashMap, TreeMap and ConcurrentHashMap. Java 21 added SequencedCollection and SequencedMap with getFirst() and getLast().
08

What is the difference between composition and inheritance, and which should you prefer?

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

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

Write a minimal Dockerfile for a Spring Boot application.

Save to ▾
Show answer
A multi-stage build keeps the image small. FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
11

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; }
12

Show runtime polymorphism with a simple Java example.

Save to ▾
Show answer
A parent reference calls the child's overridden method at runtime. abstract class Shape { abstract double area(); } class Circle extends Shape { double r = 2; double area() { return Math.PI * r * r; } } class Square extends Shape { double s = 3; double area() { return s * s; } } Shape sh = new Circle(); System.out.println(sh.area()); // Circle area
13

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

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

What is the difference between reduce() and collect()?

Save to ▾
Show answer
reduce() combines elements into a single immutable value using an identity and an associative function, such as summing numbers. collect() is a mutable reduction that accumulates into a container like a List, Map or StringBuilder, which is far more efficient for building collections. Using reduce to build a list creates many intermediate copies, so use collect for containers.
16

What is the role of the JIT compiler?

Save to ▾
Show answer
The JVM first interprets bytecode, then profiles which methods run often. The Just In Time compiler converts these hot methods into optimised native code at runtime. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation and C2 applies aggressive optimisations like inlining and escape analysis. This is why Java apps get faster after a warm-up period.
17

What is the difference between HashMap and ConcurrentHashMap?

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

Implement the Builder pattern for a User class with many optional fields.

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

Describe a situation where you had to deliver under a tight deadline.

Save to ▾
Show answer
Situation: a bulk upload feature had to go live in four days for a client launch. Task: build it safely in time. Action: I split it into must-have and later items, used an ExecutorService to process rows in parallel, wrote focused tests for validation and kept the product owner updated daily. Result: we shipped on time, it handled 50,000 rows in under two minutes and we added the extras next sprint.
20

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

How do you explain OOP concepts to a junior developer who is new to Java?

Save to ▾
Show answer
Situation: I mentored two interns who struggled with OOP. Task: help them design classes for a library app. Action: I used real objects they knew, like Book and Member, showed encapsulation with private fields, then wrote one interface with two implementations to show polymorphism, and reviewed their code daily. Result: within two weeks they designed modules on their own and their pull requests needed fewer review comments.
22

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

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

Write a sealed interface with records and a switch that computes area.

Save to ▾
Show answer
The switch needs no default because the type set is closed. sealed interface Shape permits Circle, Rect {} record Circle(double r) implements Shape {} record Rect(double w, double h) implements Shape {} static double area(Shape s) { return switch (s) { case Circle c -> Math.PI * c.r() * c.r(); case Rect(double w, double h) -> w * h; }; }
25

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

Add optimistic locking to an entity and handle the conflict.

Save to ▾
Show answer
Add a version field; Hibernate checks it on update. @Entity class Account { @Id Long id; long balance; @Version Long version; } @Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3) @Transactional public void debit(Long id, long amt) { Account a = repo.findById(id).orElseThrow(); a.balance -= amt; } The update includes WHERE version = ?, so a stale write fails and is retried.
27

Implement equals() and hashCode() for an Employee class with id and email.

Save to ▾
Show answer
Use the same fields in both methods. @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Employee e)) return false; return id == e.id && Objects.equals(email, e.email); } @Override public int hashCode() { return Objects.hash(id, email); } Pattern matching for instanceof (Java 16) avoids an explicit cast.
28

What are fail-fast and fail-safe iterators?

Save to ▾
Show answer
Fail-fast iterators, used by ArrayList and HashMap, throw ConcurrentModificationException if the collection is structurally modified during iteration other than through the iterator itself; they check a modCount. Fail-safe or weakly consistent iterators, as in ConcurrentHashMap and CopyOnWriteArrayList, work on a snapshot or tolerate changes and never throw, but may not show the latest updates.
29

Code builds a large CSV report with String += inside a loop and it is very slow. Why and what is the fix?

Save to ▾
Show answer
Each += creates a new String and copies all previous characters, so building n rows is O(n squared) in time and creates huge garbage. Use a single StringBuilder with append() inside the loop, ideally with an initial capacity, or write rows directly to a BufferedWriter for very large output. This turns minutes of work into milliseconds.
30

A query is fast in development but takes 8 seconds in production. How do you investigate?

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

Write a record with validation in its compact constructor.

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

Describe a time you had to learn a new technology quickly.

Save to ▾
Show answer
Situation: I joined a project using reactive Spring WebFlux with no prior experience. Task: contribute within two weeks. Action: I studied Project Reactor basics, built a small practice service, paired with a senior on my first ticket and kept notes on common operators. Result: I delivered my first feature in the second week and later wrote the team guide on avoiding blocking calls in reactive code.
33

A log file shows a NullPointerException only for some users. How do you debug it?

Save to ▾
Show answer
Start with the stack trace; since Java 14 helpful NPE messages name exactly which variable was null. Reproduce with the failing user's data, which often has an optional field missing. Fix the root cause by validating input at the boundary, using Optional for values that may be absent and annotating with @NonNull. Add a unit test for that data case so it does not return.
34

How does HashSet work internally?

Save to ▾
Show answer
HashSet is backed by a HashMap. Each element you add becomes a key in that map with a shared dummy object as the value. So uniqueness depends entirely on the element's hashCode() and equals(), and operations are O(1) on average. LinkedHashSet uses a LinkedHashMap to keep insertion order, and TreeSet uses a TreeMap to keep elements sorted.
35

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

Flatten a list of lists of integers and compute the sum of squares of the even numbers.

Save to ▾
Show answer
flatMap then use a primitive stream to avoid boxing. int result = lists.stream() .flatMap(List::stream) .filter(n -> n % 2 == 0) .mapToInt(n -> n * n) .sum(); mapToInt returns an IntStream, whose sum() is simpler and faster than reduce on boxed Integers.

Companies with offices in Bangalore (18)

IT services

TCS

Java interview questions

  • 30 questions
  • 4 rounds

Mumbai, Chennai, Pune +2

View questions
IT services

Infosys

Java interview questions

  • 30 questions
  • 4 rounds

Bengaluru, Mysuru, Pune +2

View questions
IT services

Wipro

Java interview questions

  • 30 questions
  • 4 rounds

Bengaluru, Hyderabad, Pune +2

View questions
Consulting

Accenture

Java interview questions

  • 30 questions
  • 4 rounds

Bengaluru, Hyderabad, Pune +2

View questions
IT services

Cognizant

Java interview questions

  • 30 questions
  • 4 rounds

Chennai, Bengaluru, Pune +2

View questions
IT services

Capgemini

Java interview questions

  • 30 questions
  • 4 rounds

Mumbai, Bengaluru, Pune +2

View questions
IT services

HCLTech

Java interview questions

  • 30 questions
  • 4 rounds

Noida, Chennai, Bengaluru +2

View questions
IT services

Tech Mahindra

Java interview questions

  • 30 questions
  • 4 rounds

Pune, Hyderabad, Bengaluru +2

View questions
IT services

LTIMindtree

Java interview questions

  • 30 questions
  • 4 rounds

Mumbai, Pune, Bengaluru +2

View questions
Product

Amazon

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Hyderabad, Chennai +2

View questions
Product

Oracle

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Hyderabad, Noida +2

View questions
Banking & finance

Goldman Sachs

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Hyderabad, Mumbai

View questions
Banking & finance

JP Morgan Chase

Java interview questions

  • 30 questions
  • 5 rounds

Mumbai, Bengaluru, Hyderabad

View questions
Banking & finance

Morgan Stanley

Java interview questions

  • 30 questions
  • 5 rounds

Mumbai, Bengaluru

View questions
Fintech

Paytm

Java interview questions

  • 30 questions
  • 5 rounds

Noida, Bengaluru, Mumbai

View questions
Fintech

PhonePe

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Pune

View questions
E-commerce & consumer tech

Flipkart

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Hyderabad

View questions
Product

SAP

Java interview questions

  • 30 questions
  • 5 rounds

Bengaluru, Gurugram, Pune +1

View questions

Frequently asked questions

Which companies hire Java professionals in Bangalore?

Companies with large offices in Bangalore include TCS, Infosys, Wipro, Accenture, Cognizant, Capgemini, HCLTech, Tech Mahindra, LTIMindtree, Amazon. Use their company pages below to practise employer-specific sets.

Are Java interviews in Bangalore different from other cities?

The questions depend more on the company than the city. Bangalore's mix of employers decides the style: Product-company interviews here are usually deeper, with more scenario, design and hands-on rounds

How do I find Java jobs in Bangalore?

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