Top 30 Java Interview Questions & Answers for Infosys (3+ Years Experience)
Updated for 2026 – Real-world explanations + examples
Infosys interviews emphasize problem-solving, Java fundamentals, collection performance, and multithreading concepts. Below are the top 30 most commonly asked Java questions for 3–5 years experience, each with concise answers + real project examples.
Q1. What are the four major OOP concepts in Java?
Answer: The four major object-oriented programming (OOP) concepts are: Encapsulation, Abstraction, Inheritance, Polymorphism.
-
Encapsulation: wrapping data (fields) and methods in a class, controlling access via modifiers (private/public).
-
Abstraction: exposing only necessary details, hiding internal implementation.
-
Inheritance: subclassing to reuse code.
-
Polymorphism: objects taking many forms — e.g., method overloading (compile time) or overriding (runtime).
Example:
Here Dog inherits from Animal. If you have Animal a = new Dog(); a.sound(); you get “Woof” (runtime polymorphism). Encapsulation example: private fields with getters/setters.
Q2. Why is String immutable in Java?
Answer: java.lang.String is immutable because once created, its value cannot be changed. Internal design: final class, internal final char[] (or byte[] in modern Java). Immutability gives benefits: thread-safety, caching (string pool), safe use as keys in collections, avoids bugs from unexpected modification.
Example:
Here s1 wasn’t changed; a new String s2 was created. If Strings were mutable, many issues would arise in multithreaded code or string pooling.
Q3. What is the difference between String, StringBuffer, and StringBuilder?
Answer:
-
Stringis immutable. -
StringBufferis mutable and thread-safe (synchronized). -
StringBuilderis mutable but not synchronized (so not thread-safe), recommended for single-thread use due to better performance.
Example:
Q4. Explain difference between compile-time polymorphism vs runtime polymorphism.
Answer:
-
Compile-time polymorphism: method overloading (same method name, different parameters) or operator overloading (not in Java for user types).
-
Runtime polymorphism: method overriding via inheritance and dynamic dispatch (at runtime the JVM decides which method to call).
Example:
Q5. What is the difference between == and .equals() in Java?
Answer:
-
==compares reference identity (whether two references point to same object in memory). -
.equals()is a method (fromObject), meant to compare logical equivalence, and can be overridden (like inString,Integer, custom classes). If not overridden, equals falls back to==.
Example:
Q6. Is Java pass-by-value or pass-by-reference?
Answer: Java is strictly pass-by-value. For primitive types, the value is copied. For object references, the value of the reference is copied (i.e., a copy of the pointer), but both refer to same object. There is no pass-by-reference in Java (i.e., you cannot change the caller’s reference to point to new object).
Example:
Q7. How does garbage collection work in Java? Explain memory structure.
Answer:
Java runtime manages memory automatically via garbage collection (GC). Major memory areas: Heap (objects), Stack (local variables + method frames), Method Area / PermGen or Metaspace (class definitions), PC register / native stacks. Objects no longer referenced become eligible for GC. There are different GC algorithms (Mark & Sweep, Generational GC, etc).
Example:
In reality you don’t force GC; you trust JVM to reclaim memory.
Q8. What is the difference between ArrayList and LinkedList in Java?
Answer:
-
ArrayListis backed by a dynamic array: good for random access (get by index) O(1), slower for insertion/removal in the middle (shifting). -
LinkedListis a doubly linked list: good for insertion/removal at head/tail/middle (if you have reference) but slower for random access (O(n)).
Also, LinkedList implements List and Deque interfaces (so you can use it as queue).
Example:
Q9. What is the difference between List, Set and Map in Java Collections?
Answer:
-
Listis an ordered collection, allows duplicates, index-based access. -
Setis a collection that does not allow duplicates, may be ordered or unordered depending on implementation (HashSet, TreeSet). -
Mapis a collection of key→value pairs; keys must be unique, values may duplicate; not a subtype of Collection.
Example:
Q10. Explain HashMap internal working in Java.
Answer:
HashMap works by using a hash table where keys are hashed to hashed-buckets (an array of Node<K,V>). Steps: compute hashCode of key, then map to bucket via index (hash & (capacity-1)). If collision (same bucket), chain via linked list or tree (since Java 8). On insertion: if load factor threshold exceeded, resize (rehash). Retrieval: compute hash, go to bucket, traverse chain comparing key equals until match.
Example:
If you insert keys whose hash map to same bucket repeatedly, performance may degrade without treeifying.
Q11. What is fail-fast vs fail-safe iterator in Java Collections?
Answer:
-
A fail-fast iterator (e.g., on
ArrayList,HashMap’s keySet) checks a modification count and throwsConcurrentModificationExceptionif collection modified structurally after iterator created. -
A fail-safe iterator (e.g., on
CopyOnWriteArrayList,ConcurrentHashMap) works on a snapshot of the collection or uses internal locking so modifications don’t cause exceptions in the iteration thread.
Example:
Contrast with CopyOnWriteArrayList which permits such modification although new element may not appear in iteration.
Q12. What is multithreading in Java? How do you create threads?
Answer:
Multithreading means executing multiple threads concurrently within a process. In Java you can create threads by:
-
Extending
Threadclass and overridingrun(), thenstart(). -
Implementing
Runnableinterface (orCallable<V>) and passing toThread(or using executor).
You also use concurrency utilities injava.util.concurrent.
Example:
Q13. What is the difference between synchronized and volatile in Java?
Answer:
-
synchronizedensures mutual exclusion and visibility: only one thread at a time can execute a synchronized block/object; it also ensures memory visibility (locks flush caches). -
volatileensures visibility of changes across threads (reads/writes go to main memory) but does not provide atomicity or locking for compound actions. So volatile is good for simple flags/shared variables; for compound state changes you need synchronization or other concurrency constructs.
Example:
If you needed to increment a counter, volatile alone wouldn’t suffice for atomic increment (use AtomicInteger or synchronized).
Q14. What is a deadlock? How can it be prevented?
Answer:
Deadlock is a situation where two or more threads are blocked forever, each waiting for a resource held by the other. In Java this can happen when Thread-A holds Lock-1 and waits for Lock-2, while Thread-B holds Lock-2 and waits for Lock-1.
Prevention strategies:
-
Acquire locks in a fixed global order.
-
Use
tryLock()with timeout. -
Use less fine-grained locking or avoid nested locks.
Example:
Q15. What are lambda expressions and functional interfaces in Java 8?
Answer:
-
A functional interface is an interface with exactly one abstract method (e.g.,
Runnable,Comparator,Consumer<T>). You can annotate with@FunctionalInterface. -
A lambda expression provides a concise way to implement a functional interface:
(parameters) -> expression/body. Java 8 introduced this. Lambdas allow treating functions as first-class citizens.
Example:
Here forEach takes a Consumer<String> functional interface.
Q16. Explain the Stream API in Java 8. What is the difference between intermediate and terminal operations?
Answer:
The Stream API allows functional‐style operations on collections (and other data sources) like map/filter/reduce. Streams are lazy: you build a pipeline of operations, and execution happens when a terminal operation is called.
-
Intermediate operations return a new stream (e.g.,
filter(),map(),sorted()), and are lazy. -
Terminal operations produce a result or side-effect (e.g.,
collect(),forEach(),reduce(),count()), and trigger the pipeline.
Example:
Q17. What is the Optional class in Java 8? Why use it?
Answer:
java.util.Optional<T> is a container object which may or may not contain a non-null value. It helps to avoid NullPointerExceptions and makes API contracts explicit: e.g., a method returns Optional<String> instead of possibly returning null. It encourages handling absence of value.
Example:
Q18. Explain method overloading vs method overriding in Java.
Answer:
-
Method overloading (compile time): same method name, different parameter list (type/number) within same class or subclass.
-
Method overriding (runtime polymorphism): subclass provides a specific implementation for a method declared in superclass (same name + signature).
Example:
Q19. What is the difference between abstract class and interface in Java (pre Java 8 vs post Java 8)?
Answer:
-
Abstract class: can have concrete methods, fields, constructors, and may hold state. A class extends only one abstract class (single inheritance).
-
Interface: initially (pre Java 8) only abstract methods; Java 8 introduced default & static methods; Java 9 added private methods; allows multiple inheritance of types (a class can implement many interfaces).
Use interface when you want to define contract, and abstract class when you want shared code/state plus derived classes.
Example:
Q20. What are the new features in Java 8 (besides lambdas and streams)?
Answer: Some of the key features include: default and static methods in interfaces, method references, Optional, new Date/Time API (java.time.*), CompletableFuture, ParallelStream, Collectors utilities, StringJoiner, enhancements to Collection interface (forEach, removeIf), and more.
Example:
or:
Q21. Explain the difference between Array and ArrayList.
Answer:
-
Array: fixed size once created (
new int[5]). Can hold primitives or objects. -
ArrayList: resizable dynamic array (part of Java Collections), cannot hold primitives directly (use wrapper types), offers methods (add, remove, etc), size dynamically changes.
Example:
Q22. What is the difference between == vs equals() for custom objects? How do you override equals() and hashCode()?
Answer:
As earlier, == checks reference equality, equals() checks logical equality. For custom objects you should override equals() and hashCode() so that objects used as keys in hash-based collections behave correctly (contract: equal objects must equal hashCode).
Example:
Q23. What is a classloader in Java? How does the JVM load classes?
Answer:
A classloader is a part of the JVM that loads class files (binary) into the runtime. Three main types: Bootstrap, Extension, Application (or System) classloader. The loading process: loading → linking (verification, preparation, resolution) → initialization (static blocks executed). Custom classloaders can be used.
Example:
This triggers the classloader to load the class (if not already), link it, then initialize it.
Q24. What is reflection in Java? When do you use it?
Answer:
Reflection (in java.lang.reflect) is the ability of a program to inspect and modify runtime behavior: inspect classes, methods, fields, call methods dynamically, even if private (via setAccessible). Useful for frameworks (ORMs, DI), serialization, testing. But it has overhead and breaks encapsulation.
Example:
Q25. What is serialization in Java? Why and how is it done?
Answer:
Serialization is the process of converting an object into a stream of bytes (so it can be written to file/network) and deserialization is the reverse. In Java you implement java.io.Serializable (marker interface). You can use ObjectOutputStream and ObjectInputStream. It is used for caching, transmitting objects, deep cloning, etc.
Example:
Then:
Q26. What is the difference between shallow copy vs deep copy in Java?
Answer:
-
Shallow copy: copies the object but not the objects it refers to (i.e., references inside the object still point to original).
-
Deep copy: copies the object and recursively copies all objects it references, so the clone is independent of the original.
Example:
Here addr is same in clone & original. For deep copy you’d clone the Address as well.
Q27. What is thread-safety? Give an example of a thread-safe collection.
Answer:
Thread-safety means that a class or collection can be safely used by multiple threads simultaneously without causing inconsistent state or race conditions. Example of thread-safe collection: java.util.concurrent.ConcurrentHashMap, CopyOnWriteArrayList, Vector (legacy), Hashtable.
Example:
Q28. What is the difference between HashMap and ConcurrentHashMap?
Answer:
-
HashMapis not thread‐safe; if accessed concurrently with modifications without proper synchronization, behavior is undefined. -
ConcurrentHashMapis thread‐safe and uses internal locking mechanics (or lock‐free in parts) to allow concurrent reads/writes with better scalability. It does not lock entire map for modifications, uses segment or bin‐level locks (Java 8 uses internal table + CAS). Alsonullkeys/values are not allowed inConcurrentHashMap(unlikeHashMap).
Example:
Q29. What is the difference between checked vs unchecked exceptions in Java?
Answer:
-
Checked exceptions extend
Exception(but notRuntimeException) and must be either caught or declared to be thrown by the method signature. -
Unchecked exceptions extend
RuntimeException(orError) and need not be declared or caught explicitly; they usually indicate programming errors (null pointer, array out of bounds).
Example:
Q30. What are default methods in interfaces (Java 8)? Why were they introduced?
Answer:
Default methods let you add concrete methods (with implementation) in interfaces by using the keyword default. They were introduced in Java 8 to support backward compatibility: to add new methods to existing interfaces (like Collection, Iterable) without breaking existing implementations. They also allow interfaces to provide some common behavior.
Example:
⭐ Conclusion
These 30 Java interview questions represent the most commonly asked topics at Infosys for 3+ years experience—with a strong focus on:
✔ Collections
✔ Multithreading
✔ Lambda & Streams
✔ Memory management
✔ OOP & Core Java fundamentals
Comments
Post a Comment