Skip to content

Cognizant Java Interview Questions & Answers

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

About Cognizant hiring for Java roles

Cognizant is a US-headquartered IT services and consulting company with most of its workforce based in India. It provides application development, testing, cloud, digital engineering and data analytics services, with strong practices in healthcare, insurance and banking. In India it hires for programmer analyst, quality engineer and data roles through campus and off-campus programmes such as GenC.

For Java roles, this Cognizant practice set focuses most on Java Basics and JVM (6), Strings and Exception Handling (6), Multithreading and Concurrency (5), Collections Framework (4). It has 14 easy, 14 medium, 2 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Teaneck, New Jersey, USA
Main India offices
Chennai, Bengaluru, Pune, Hyderabad, Kolkata

Cognizant Java interview process

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

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

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

Why is the main method public static void?

Save to ▾
Show answer
It is public so the JVM can call it from outside the class, static so it can run without creating an object, and void because it returns nothing to the JVM; exit codes are set with System.exit(). The String[] args parameter receives command line arguments. From Java 21 onward, preview features allow simpler instance main methods for learning.
02

Count the frequency of each character in a string using Java.

Save to ▾
Show answer
A map with merge() is simple; streams also work. Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.merge(c, 1, Integer::sum); } // Streams version Map<Character, Long> f = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); LinkedHashMap keeps first-seen order.
03

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

Implement an LRU cache using LinkedHashMap.

Save to ▾
Show answer
Access order plus removeEldestEntry gives LRU in a few lines. class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; LruCache(int capacity) { super(16, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > capacity; } } get and put are O(1).
05

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

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

What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?

Save to ▾
Show answer
List.of() returns a truly immutable list; add, set and remove throw exceptions and nulls are not allowed. Arrays.asList() returns a fixed-size list backed by the array: set() works and writes through to the array, but add() and remove() throw. Collections.unmodifiableList() is a read-only view, so changes to the original list are still visible through it.
08

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

What is the difference between start() and run()?

Save to ▾
Show answer
start() asks the JVM to create a new thread and then calls run() on that new thread, so the code executes concurrently. Calling run() directly is just a normal method call on the current thread, so no new thread is created. Calling start() twice on the same Thread throws IllegalThreadStateException.
10

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

Write a Java program to check whether a number is prime.

Save to ▾
Show answer
Check divisibility only up to the square root, which makes it O(sqrt n). public static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (int i = 3; (long) i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } The long cast avoids overflow for large n.
12

What is CompletableFuture and how is it better than Future?

Save to ▾
Show answer
Future only lets you block with get() to obtain a result. CompletableFuture supports non-blocking composition: thenApply to transform, thenCompose to chain async calls, thenCombine or allOf to join several, and exceptionally or handle for errors. It runs on the common ForkJoinPool by default, but pass your own executor for blocking I/O to avoid starving the pool.
13

Write code to check if two strings are anagrams.

Save to ▾
Show answer
Count characters with an array for lowercase letters. public static boolean isAnagram(String a, String b) { if (a.length() != b.length()) return false; int[] count = new int[26]; for (int i = 0; i < a.length(); i++) { count[a.charAt(i) - 'a']++; count[b.charAt(i) - 'a']--; } for (int c : count) if (c != 0) return false; return true; } O(n) time; use a HashMap for Unicode input.
14

Print numbers 1 to 10 alternately from two threads (odd and even).

Save to ▾
Show answer
Use a shared lock with wait and notify. class Printer { int n = 1; synchronized void print(boolean odd) throws InterruptedException { while (n <= 10) { if ((n % 2 == 1) == odd) { System.out.println(Thread.currentThread().getName() + " " + n++); notifyAll(); } else wait(); } notifyAll(); } } Start one thread with print(true) and another with print(false).
15

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

Compare String, StringBuilder and StringBuffer.

Save to ▾
Show answer
String is immutable and thread safe by design. StringBuilder is mutable and not synchronized, so it is the fastest choice for building strings in a single thread, such as in loops. StringBuffer is mutable and synchronized, so it is thread safe but slower, and is rarely needed today. The compiler already optimises simple + concatenation outside loops.
19

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

Explain the main memory areas of the JVM.

Save to ▾
Show answer
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
21

What does the var keyword do and where can it not be used?

Save to ▾
Show answer
var, added in Java 10, lets the compiler infer the type of a local variable from its initializer, for example var list = new ArrayList<String>(). Java stays statically typed. var cannot be used for fields, method parameters or return types, and it needs an initializer that is not null. Use it when the type is obvious to keep code readable.
22

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

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

What is constructor chaining?

Save to ▾
Show answer
Constructor chaining is calling one constructor from another. this(...) calls another constructor in the same class and super(...) calls a parent class constructor; either must be the first statement. If you write neither, the compiler inserts super() automatically. Chaining avoids duplicate initialisation code, for example a no-arg constructor calling this("default", 0).
25

How do you handle disagreement with a reviewer about your code?

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

Write a Spring Data JPA repository method that fetches orders with items to avoid N+1.

Save to ▾
Show answer
Use JOIN FETCH or an entity graph. public interface OrderRepository extends JpaRepository<Order, Long> { @Query("select distinct o from Order o join fetch o.items where o.customerId = :cid") List<Order> findWithItems(@Param("cid") Long customerId); @EntityGraph(attributePaths = "items") List<Order> findByStatus(String status); } Both load orders and items in one query.
27

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

What is Spring Boot Actuator used for?

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

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

How does @Transactional work and what are its common pitfalls?

Save to ▾
Show answer
@Transactional is applied through a proxy that opens a transaction before the method and commits or rolls back after. Pitfalls: calling a transactional method from the same class bypasses the proxy, so no transaction starts; by default rollback happens only for unchecked exceptions; it works on public methods; and long transactions with remote calls hold connections. Use propagation and readOnly where suitable.

Tips to crack the Cognizant Java interview

  • Understand the GenC, GenC Next and GenC Elevate tracks so you know which skills and coding level each role expects.
  • Revise SQL queries, OOP concepts and basic testing terminology since many freshers are placed in development or QA projects.
  • Read about Cognizant's healthcare and life sciences domain work, which is a large part of its client base.
  • 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; Cognizant interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Cognizant Java interview?

Candidates usually go through 4 stages: Online assessment (aptitude + reasoning); Coding assessment; 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 Cognizant Java interview?

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

Are these the exact questions asked at Cognizant?

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

Where does Cognizant hire Java professionals in India?

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

Java questions for similar companies