Skip to content

Tech Mahindra Java Interview Questions & Answers

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

About Tech Mahindra hiring for Java roles

Tech Mahindra is an Indian IT services and consulting company and part of the Mahindra Group. It is known for its strong telecom and communications practice and also serves banking, manufacturing and healthcare clients. In India it hires for software engineers, test engineers, network engineers, data analysts and data engineers.

For Java roles, this Tech Mahindra practice set focuses most on Java Basics and JVM (7), Collections Framework (6), Strings and Exception Handling (5), Java 8+ Features and Streams (4). It has 10 easy, 19 medium, 1 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Pune, India
Main India offices
Pune, Hyderabad, Bengaluru, Noida, Chennai

Tech Mahindra Java interview process

  1. Online assessment (aptitude + English essay)
  2. Coding test
  3. Technical interview
  4. HR round

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

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

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

What is the difference between Comparable and Comparator?

Save to ▾
Show answer
Comparable defines a class's natural ordering through compareTo() inside the class, such as String sorted alphabetically. Comparator is a separate object with compare(), so you can define many orderings without changing the class. Java 8 made Comparator easy: Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getName). TreeMap and sort methods accept either.
06

Why are String objects immutable in Java?

Save to ▾
Show answer
Strings are immutable so they can be safely shared from the string pool, used as HashMap keys with a cached hash code, passed between threads without locking and trusted in security checks such as file paths and class names. Any change, like concat or replace, creates a new String. For heavy modification use StringBuilder, which changes its internal buffer in place.
07

Tell me about a time a production incident happened because of your code.

Save to ▾
Show answer
Situation: a release I made caused failed payments for some users. Task: restore service and find the cause fast. Action: I rolled back within ten minutes, then found I had not handled a null bank code from one partner, which threw an exception. I fixed it, added validation and a test with that partner's data and shared a short write-up. Result: no repeat and the team added null checks to our review checklist.
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

What is the difference between == and equals() in Java?

Save to ▾
Show answer
== compares primitive values, or for objects it checks whether two references point to the same object in memory. equals() checks logical equality and can be overridden, as String, Integer and most value classes do. For example, new String("a") == new String("a") is false, but equals() returns true. Always use equals() to compare object content.
10

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

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

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

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

What is the difference between HashMap, LinkedHashMap and TreeMap?

Save to ▾
Show answer
HashMap gives O(1) average operations with no ordering guarantee. LinkedHashMap keeps insertion order, or access order if configured, which helps build an LRU cache. TreeMap keeps keys sorted by natural order or a Comparator with O(log n) operations and supports range methods like floorKey and headMap. HashMap allows one null key; TreeMap does not allow null keys with natural ordering.
15

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

What is the String constant pool?

Save to ▾
Show answer
The string pool is a special area in the heap where string literals are stored once and reused. String a = "hi" and String b = "hi" point to the same object. new String("hi") creates a separate heap object, and intern() returns the pooled copy. Pooling saves memory because many strings in apps repeat, such as status codes and keys.
17

Find the second highest salary from a list of employees using streams.

Save to ▾
Show answer
Sort distinct salaries in descending order and skip one. Optional<Integer> second = employees.stream() .map(Employee::salary) .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); This returns empty if fewer than two distinct salaries exist. For huge data a single pass tracking top two is O(n).
18

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

How does Spring Boot auto-configuration work?

Save to ▾
Show answer
At startup Spring Boot reads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each class uses conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so it creates beans only when the library is on the classpath and you have not defined your own. Run with --debug to see the condition report showing what was applied and why.
20

Why is Java called platform independent?

Save to ▾
Show answer
javac compiles source code into bytecode, not native machine code. Any machine with a compatible JVM can run that same .class file, so the code is written once and run anywhere. The JVM itself is platform specific; there are separate JVM builds for Windows, Linux and macOS, but the bytecode they run is identical.
21

Write a JDBC batch insert for a list of products.

Save to ▾
Show answer
Batching sends many rows in one round trip. String sql = "INSERT INTO product(name, price) VALUES (?, ?)"; try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { c.setAutoCommit(false); int n = 0; for (Product p : products) { ps.setString(1, p.name()); ps.setLong(2, p.price()); ps.addBatch(); if (++n % 500 == 0) ps.executeBatch(); } ps.executeBatch(); c.commit(); }
22

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

How does HashMap work internally?

Save to ▾
Show answer
HashMap stores entries in an array of buckets. It computes the key's hashCode(), spreads the bits and picks a bucket index. Collisions are stored as a linked list in the bucket, and since Java 8 a bucket with more than 8 entries (when the table has at least 64 buckets) becomes a red-black tree, making the worst case O(log n). When size passes capacity times load factor 0.75, it resizes to double.
24

What is the contract between equals() and hashCode()?

Save to ▾
Show answer
If two objects are equal by equals(), they must return the same hashCode(). Unequal objects may share a hash code, but fewer collisions give better performance. If you override equals() but not hashCode(), HashMap and HashSet break: an equal key lands in a different bucket and cannot be found. Use the same fields in both methods, or use records, which generate both.
25

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

Your application hangs and CPU is near zero. How do you find out why?

Save to ▾
Show answer
Low CPU with a hang suggests threads are blocked, often a deadlock or waiting on a slow resource. Take several thread dumps with jcmd pid Thread.print. The JVM reports detected deadlocks at the end of the dump. Otherwise look for many threads BLOCKED on the same lock or WAITING on a connection pool or socket read, then fix lock order, add timeouts or increase the pool.
27

What is the difference between synchronized and ReentrantLock?

Save to ▾
Show answer
synchronized is a built-in keyword that locks a monitor and releases it automatically at block exit. ReentrantLock is an explicit lock that adds tryLock with timeout, interruptible locking, fairness options and multiple Condition objects, but you must unlock in a finally block. Both are reentrant. Prefer synchronized for simple cases and ReentrantLock when you need its extra features.
28

What is autoboxing and what pitfall can it cause?

Save to ▾
Show answer
Autoboxing is automatic conversion between a primitive and its wrapper, such as int to Integer, and unboxing is the reverse. A common pitfall is a NullPointerException when unboxing a null Integer. Another is comparing Integer objects with ==, which works only for cached values from -128 to 127. Boxing inside tight loops also creates extra garbage and slows code.
29

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()).
30

What is the difference between final, finally and finalize?

Save to ▾
Show answer
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try-catch whether or not an exception occurs, used for cleanup. finalize() was a method called before garbage collection; it is deprecated for removal and should be replaced with try-with-resources or Cleaner.

Tips to crack the Tech Mahindra Java interview

  • Read about telecom basics like 4G, 5G and network operations, since communications is Tech Mahindra's largest vertical.
  • Practise English essay and verbal ability sections, which often appear in Tech Mahindra online assessments.
  • Revise SQL and one programming language, and prepare a clear two-minute explanation of your project.
  • 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; Tech Mahindra interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Tech Mahindra Java interview?

Candidates usually go through 4 stages: Online assessment (aptitude + English essay); Coding test; Technical interview; 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 Tech Mahindra Java interview?

This practice set leans on Java Basics and JVM (7), Collections Framework (6), Strings and Exception Handling (5), Java 8+ Features and Streams (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Tech Mahindra interviewers ask you to walk through real work.

Are these the exact questions asked at Tech Mahindra?

No. These are curated practice questions that match the skills and difficulty usually tested in it services interviews like Tech Mahindra's. They are not a leaked or verified list of past questions.

Where does Tech Mahindra hire Java professionals in India?

Tech Mahindra has large teams in Pune, Hyderabad, Bengaluru, Noida, Chennai. Openings and locations change often, so check the Tech Mahindra careers page and filter by city and experience.

Java questions for similar companies