0% found this document useful (0 votes)
1 views21 pages

Infosys Java Developer Interview Prep

The document is an Interview Preparation Guide covering essential Java concepts, including OOP principles, Java Collections Framework, Java 8+ features, multithreading, JVM internals, exception handling, design patterns, and SQL database concepts. It provides a structured approach to prepare for interviews, particularly for Infosys, with key points, examples, and best practices. Each section is detailed with important topics and practical coding examples to aid understanding and application.

Uploaded by

virendiranr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views21 pages

Infosys Java Developer Interview Prep

The document is an Interview Preparation Guide covering essential Java concepts, including OOP principles, Java Collections Framework, Java 8+ features, multithreading, JVM internals, exception handling, design patterns, and SQL database concepts. It provides a structured approach to prepare for interviews, particularly for Infosys, with key points, examples, and best practices. Each section is detailed with important topics and practical coding examples to aid understanding and application.

Uploaded by

virendiranr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interview Preparation Guide

■ Java Core ■■ SQL & DB ■ Multithreading ■ Spring Boot

OOP · Collections Joins · Indexes Threads · Sync REST · DI · JPA


Streams · JVM Transactions · SP Executors · Lock Microservices

■ Table of Contents
1. Java Core Concepts & OOP
2. Java Collections Framework
3. Java 8+ Features (Streams, Lambdas, Optional)
4. Multithreading & Concurrency
5. JVM Internals & Memory Management
6. Exception Handling
7. Design Patterns
8. SQL & Database Concepts
9. Programming Questions (Java)
10. Infosys Interview Q&A; – Java
11. Infosys Interview Q&A; – SQL
12. Quick Revision Cheatsheet
1. Java Core Concepts & OOP
Fundamentals every Infosys Java Developer must know

1.1 Four Pillars of OOP


Pillar Definition Java Example

Encapsulation Bundling data + methods; restrict direct access private fields + getters/setters

Abstraction Hiding implementation, exposing only interface abstract class / interface

Inheritance Child class acquires properties of parent class Dog extends Animal

Polymorphism One interface, many implementations method overloading & overriding

1.2 Interface vs Abstract Class


Feature Interface Abstract Class

Methods All abstract (default/static allowed from Can have concrete + abstract
Java 8)

Variables public static final only Any access modifier

Constructor Not allowed Allowed

Multiple Inheritance Supported Not supported

Use when Defining a contract/capability Sharing common base code

1.3 Key OOP Interview Points


• Overloading vs Overriding: Overloading = same method name, different params (compile-time). Overriding
= subclass redefines parent method (runtime).
• final keyword: final class = cannot be extended; final method = cannot be overridden; final variable =
constant.
• static keyword: static belongs to class, not object. static methods cannot access instance variables.
• this vs super: this refers to current object; super refers to parent class constructor/method.
• Constructor chaining: Using this() to call another constructor in same class, or super() to call parent
constructor.
• Cohesion & Coupling: High cohesion (focused class) + Low coupling (minimal dependency) = good design.

1.4 Java Memory Model


Stack: Stores local variables, method call frames. Each thread has its own stack.
Heap: Stores objects (new keyword). Shared across threads. Managed by GC.
Method Area (Metaspace): Stores class metadata, static variables, constants.
String Pool: A cache in Heap for String literals — why String is immutable.
2. Java Collections Framework
List, Set, Map, Queue — internals & complexity

2.1 Collection Hierarchy


Iterable → Collection
■■■ List: ArrayList, LinkedList, Vector, Stack
■■■ Set: HashSet, LinkedHashSet, TreeSet
■■■ Queue: PriorityQueue, ArrayDeque, LinkedList
Map (separate hierarchy): HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap

2.2 Complexity Cheat Sheet


Class Get/Access Add Remove Contains Notes

ArrayList O(1) O(1) amort. O(n) O(n) Dynamic array; best random
access

LinkedList O(n) O(1) head/tail O(1) node O(n) Doubly-linked; fast


insert/delete

HashMap O(1) avg O(1) avg O(1) avg O(1) avg No order; null key allowed

TreeMap O(log n) O(log n) O(log n) O(log n) Sorted by key; Red-Black


tree

HashSet – O(1) avg O(1) avg O(1) avg Backed by HashMap

TreeSet – O(log n) O(log n) O(log n) Sorted; no duplicates

PriorityQueue O(1) peek O(log n) O(log n) O(n) Min-heap by default

2.3 HashMap Internals (Most Asked!)


HashMap uses an array of Node<K,V> (buckets). On put(key, value):
1. Compute hash([Link]()) to find bucket index.
2. If bucket empty → insert. If collision → add to linked list (Java 8+: converts to Red-Black tree when chain
>= 8 nodes).
3. Load factor default = 0.75. When 75% full → rehash (double capacity).
Why override equals + hashCode? HashMap uses hashCode() to find bucket and equals() to confirm key
match. If you only override one, correctness breaks.

2.4 Fail-Fast vs Fail-Safe Iterators


Property Fail-Fast Fail-Safe

Modification during Throws ConcurrentModificationException Allowed — works on copy


iteration

Examples ArrayList, HashMap CopyOnWriteArrayList,


ConcurrentHashMap
Memory No extra memory Clones the collection
3. Java 8+ Features
Lambdas, Streams, Optional, Functional Interfaces

3.1 Lambda Expressions & Functional Interfaces


A functional interface has exactly one abstract method (@FunctionalInterface). Lambdas provide concise
anonymous implementations.

// Traditional
Comparator<String> c = new Comparator<String>() {
public int compare(String a, String b) { return [Link](b); }
};

// Lambda equivalent
Comparator<String> c = (a, b) -> [Link](b);

// Built-in functional interfaces


Predicate<String> isEmpty = s -> [Link](); // test()
Function<String,Integer> len = s -> [Link](); // apply()
Consumer<String> print = s -> [Link](s); // accept()
Supplier<String> hello = () -> "Hello"; // get()

3.2 Stream API


List<Integer> nums = [Link](1,2,3,4,5,6,7,8,9,10);

// Filter even, square them, collect


List<Integer> result = [Link]()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect([Link]()); // [4, 16, 36, 64, 100]

// Sum using reduce


int sum = [Link]().reduce(0, Integer::sum);

// Group by even/odd
Map<Boolean,List<Integer>> grouped = [Link]()
.collect([Link](n -> n % 2 == 0));

// flatMap – flatten nested lists


List<List<Integer>> nested = ...;
List<Integer> flat =
[Link]().flatMap(Collection::stream).collect([Link]());

3.3 Optional
Optional avoids NullPointerException by wrapping a value that may or may not be present.
[Link](value) – throws NPE if null
[Link](value) – safe; wraps null
[Link]() / isEmpty() – check
[Link](default) – get value or default
[Link](consumer) – run if present
[Link](fn) – transform if present

3.4 Other Java 8+ Features


Feature Description

Default Methods interface can have default method body — no breaking


existing implementations

Method References Shortcut for lambdas: ClassName::method,


instance::method, Class::new

Date/Time API [Link]: LocalDate, LocalDateTime, ZonedDateTime


(replaces deprecated Date)

CompletableFuture Async non-blocking computation; chain with thenApply,


thenCompose, exceptionally

Var (Java 10) Local variable type inference: var list = new
ArrayList<String>()

Record (Java 14+) Immutable data class: record Point(int x, int y) {}

Sealed classes (17) Restrict which classes can extend/implement

Text Blocks (15) Multi-line strings with triple quotes """ ... """
4. Multithreading & Concurrency
Thread lifecycle, synchronization, Executor framework

4.1 Thread Lifecycle


NEW → RUNNABLE → RUNNING → BLOCKED/WAITING/TIMED_WAITING → TERMINATED
• NEW: Thread object created, start() not called yet.
• RUNNABLE: After start() — ready to run, waiting for CPU.
• RUNNING: Thread scheduler picks it — executing run().
• BLOCKED: Waiting for monitor lock (synchronized block).
• WAITING: Indefinitely waiting — wait(), join().
• TIMED_WAITING: sleep(ms), wait(ms), join(ms).
• TERMINATED: run() completes or exception thrown.

4.2 Creating Threads


// 1. Extend Thread
class MyThread extends Thread {
public void run() { [Link]("Thread: " + [Link]().getName()); }
}
new MyThread().start();

// 2. Implement Runnable (preferred)


Thread t = new Thread(() -> [Link]("Lambda thread"));
[Link]();

// 3. Callable + Future (returns result)


ExecutorService exec = [Link](4);
Future<Integer> future = [Link](() -> 42);
[Link]([Link]()); // blocks until done
[Link]();

4.3 Synchronization
// synchronized method – locks 'this'
public synchronized void increment() { count++; }

// synchronized block – fine-grained lock


public void increment() {
synchronized(this) { count++; }
}

// volatile – ensures visibility across threads (not atomicity!)


private volatile boolean running = true;

// AtomicInteger – atomic compound operations


AtomicInteger counter = new AtomicInteger(0);
[Link](); // thread-safe

4.4 Executor Framework & Thread Pools


Factory Method Behaviour

[Link](n) Fixed n threads; queue excess tasks

[Link]() Unlimited threads; reuse idle ones; good for short tasks

[Link]() 1 thread, FIFO order

[Link](n) Schedule tasks with delay/period

new ThreadPoolExecutor(...) Full control: corePool, maxPool, queue, handler

4.5 Deadlock, Livelock, Starvation


Problem Cause Prevention

Deadlock Two threads hold lock A/B and wait for B/A Lock ordering, timeout, tryLock()

Livelock Threads keep reacting to each other without Add randomness/backoff


progress

Starvation Low-priority thread never gets CPU time Fair locks (ReentrantLock fair=true)
5. JVM Internals & Garbage Collection
ClassLoader, GC algorithms, performance tuning

5.1 JVM Architecture


Class Loader Subsystem: Bootstrap → Extension → Application (parent delegation model)
Runtime Data Areas: Heap, Stack, Method Area, PC Register, Native Method Stack
Execution Engine: Interpreter + JIT Compiler (HotSpot compiles hot methods to native)
Garbage Collector: Manages Heap — Eden, Survivor (S0/S1), Old Gen, Metaspace

5.2 Garbage Collection Algorithms


When to Use Key Feature

Single-threaded, small apps Simple, stop-the-world

Throughput focused (default) Multi-threaded minor GC

+) Large heaps, balanced latency Region-based, concurrent

) Ultra-low latency (<1ms pause) Concurrent, scalable

Low pause time Concurrent compaction

5.3 String Pool & Immutability


String a = "hello"; // from String Pool
String b = "hello"; // same pool reference
String c = new String("hello"); // new Heap object
[Link](a == b); // true (same reference)
[Link](a == c); // false (different object)
[Link]([Link](c)); // true (same content)

// Use StringBuilder for mutable string building — O(n) vs O(n^2) for + concatenation in
loop
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) [Link](i);
6. Exception Handling
Checked vs Unchecked, custom exceptions, best practices

6.1 Exception Hierarchy


Throwable
■■■ Error — OutOfMemoryError, StackOverflowError (don't catch!)
■■■ Exception
■■■ Checked — IOException, SQLException, ClassNotFoundException (must handle)
■■■ RuntimeException (Unchecked) — NullPointerException, ArrayIndexOutOfBoundsException,
IllegalArgumentException, ClassCastException (handle optionally)

6.2 try-with-resources & Custom Exception


// Auto-closes resources implementing AutoCloseable
try (Connection conn = [Link](url);
PreparedStatement ps = [Link](sql)) {
// use conn, ps
} // conn and ps auto-closed here

// Custom checked exception


public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: " + amount);
[Link] = amount;
}
public double getAmount() { return amount; }
}
7. Design Patterns
Singleton, Factory, Builder, Observer — Infosys favourites

7.1 Singleton Pattern (Thread-Safe)


public class Singleton {
// Double-checked locking
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized ([Link]) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}

7.2 Factory & Builder Patterns


// Factory — hide creation logic
interface Shape { void draw(); }
class ShapeFactory {
public static Shape getShape(String type) {
return switch(type) {
case "Circle" -> new Circle();
case "Square" -> new Square();
default -> throw new IllegalArgumentException(type);
};
}
}

// Builder — construct complex objects step by step


Person person = new [Link]("Alice")
.age(30).email("alice@[Link]").build();

7.3 Common Patterns Quick Reference


Pattern Type Purpose

Singleton Creational One instance globally

Factory Method Creational Delegate object creation to subclass

Abstract Factory Creational Family of related objects

Builder Creational Step-by-step complex object construction

Prototype Creational Clone existing object

Adapter Structural Convert incompatible interface

Decorator Structural Add behaviour at runtime


Facade Structural Simplify complex subsystem

Observer Behavioural Event-driven notification

Strategy Behavioural Interchangeable algorithms

Template Method Behavioural Define skeleton, override steps


8. SQL & Database Concepts
Joins, Indexes, Transactions, Stored Procedures, Optimization

8.1 SQL Joins


Join Type Returns

INNER JOIN Rows matching in BOTH tables

LEFT JOIN All rows from left + matching from right (NULL for
non-match)

RIGHT JOIN All rows from right + matching from left

FULL OUTER JOIN All rows from both tables; NULL where no match

CROSS JOIN Cartesian product — every combination

SELF JOIN Table joined with itself (e.g., employee-manager)

8.2 Important SQL Queries


-- 2nd highest salary
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);

-- N-th highest salary (generic)


SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET N-1;

-- Find duplicates
SELECT email, COUNT(*) FROM employees GROUP BY email HAVING COUNT(*) > 1;

-- Department wise max salary


SELECT dept_id, MAX(salary) AS max_sal FROM employees GROUP BY dept_id;

-- Employees without a department (LEFT JOIN)


SELECT [Link] FROM employees e LEFT JOIN departments d ON e.dept_id = [Link]
WHERE [Link] IS NULL;

-- Running total (Window function)


SELECT name, salary, SUM(salary) OVER (ORDER BY hire_date) AS running_total FROM
employees;

-- Rank employees by salary in each department


SELECT name, dept_id, salary,
RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees;

8.3 Indexes
Clustered Index: Data rows stored in index order (one per table — usually PK).
Non-Clustered Index: Separate structure pointing to data rows; multiple allowed.
Composite Index: Index on multiple columns; leftmost prefix rule applies.
Covering Index: Index includes all columns needed by query — no table lookup needed.
When to index: Frequently searched/joined/filtered columns.
When NOT to index: High write tables, small tables, columns with low cardinality.

8.4 ACID Properties & Transaction Isolation


Property Meaning

Atomicity All or nothing — transaction fully commits or fully rolls


back

Consistency DB moves from one valid state to another; constraints


always satisfied

Isolation Concurrent transactions appear serial; controlled by


isolation level

Durability Committed data persists even after crash (WAL / redo


log)

Isolation Level Dirty Read Non-Repeatable Read Phantom Read

READ UNCOMMITTED Yes Yes Yes

READ COMMITTED No Yes Yes

REPEATABLE READ (MySQL default) No No Yes

SERIALIZABLE No No No

8.5 Stored Procedures & Normalization


-- Stored procedure example
DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(IN dept_id INT)
BEGIN
SELECT * FROM employees WHERE department_id = dept_id;
END //
DELIMITER ;
CALL GetEmployeesByDept(10);

Normal Forms:
1NF: Atomic values, no repeating groups.
2NF: 1NF + no partial dependency on composite key.
3NF: 2NF + no transitive dependency (non-key → non-key).
BCNF: Stronger 3NF — every determinant is a candidate key.
9. Programming Questions
Common coding problems asked at Infosys Java interviews

Reverse a String without using reverse()


public static String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = [Link]()-1; i >= 0; i--)
[Link]([Link](i));
return [Link]();
}

Check if a String is a Palindrome


public static boolean isPalindrome(String s) {
int l = 0, r = [Link]()-1;
while (l < r) {
if ([Link](l++) != [Link](r--)) return false;
}
return true;
}

Find duplicate characters in a String


public static void findDuplicates(String s) {
Map<Character,Integer> map = new LinkedHashMap<>();
for (char c : [Link]())
[Link](c, 1, Integer::sum);
[Link]().stream()
.filter(e -> [Link]() > 1)
.forEach(e -> [Link]([Link]() + " : " + [Link]()));
}

Fibonacci – iterative and recursive


// Iterative O(n)
public static int fibIter(int n) {
int a = 0, b = 1;
for (int i = 2; i <= n; i++) { int c = a+b; a = b; b = c; }
return b;
}
// Memoized recursive O(n)
Map<Integer,Integer> memo = new HashMap<>();
public int fib(int n) {
if (n <= 1) return n;
return [Link](n, k -> fib(k-1) + fib(k-2));
}

Two Sum – find pair that sums to target


public static int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int complement = target - nums[i];
if ([Link](complement))
return new int[]{[Link](complement), i};
[Link](nums[i], i);
}
return new int[]{};
}

Find first non-repeating character in String


public static char firstUnique(String s) {
Map<Character,Integer> count = new LinkedHashMap<>();
for (char c : [Link]()) [Link](c, 1, Integer::sum);
for ([Link]<Character,Integer> e : [Link]())
if ([Link]() == 1) return [Link]();
return '\0';
}

Anagram check
public static boolean isAnagram(String s1, String s2) {
if ([Link]() != [Link]()) return false;
int[] freq = new int[256];
for (char c : [Link]()) freq[c]++;
for (char c : [Link]()) if (--freq[c] < 0) return false;
return true;
}

Binary Search
public static int binarySearch(int[] arr, int target) {
int lo = 0, hi = [Link] - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}

Producer-Consumer using BlockingQueue


BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// Producer
Runnable producer = () -> {
try { [Link](42); } catch (InterruptedException e) {
[Link]().interrupt(); }
};
// Consumer
Runnable consumer = () -> {
try { int val = [Link](); [Link](val); }
catch (InterruptedException e) { [Link]().interrupt(); }
};
new Thread(producer).start(); new Thread(consumer).start();
Singleton with Enum (Best Practice)
public enum DatabaseConnection {
INSTANCE;
public void query(String sql) { /* ... */ }
}
// Usage:
[Link]("SELECT 1");
// Thread-safe, serialization-safe, reflection-safe — preferred approach
10. Infosys Interview Q&A; — Java
In-depth answers to most frequently asked questions

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


A: Ans: == compares object references (memory addresses). equals() compares the logical content of objects.
For String, == may return false for two identical strings created with new, but equals() returns true. Always use
equals() for String comparison.
Q: Why is String immutable in Java?
A: Ans: String immutability ensures (1) String Pool caching and reuse, (2) thread-safety without synchronization,
(3) security — class names, network connections can't be altered. Achieved by making String final and storing
characters in a final byte[] array.
Q: What is the difference between HashMap and ConcurrentHashMap?
A: Ans: HashMap is not thread-safe; concurrent modifications can cause data corruption or infinite loops.
ConcurrentHashMap (Java 5+) uses segment-level locking (Java 7) / bucket-level CAS (Java 8+) to allow
concurrent reads without locking and partial locking on writes, giving far better throughput than synchronized
HashMap.
Q: What is the difference between ArrayList and LinkedList?
A: Ans: ArrayList uses a dynamic array — O(1) random access, O(n) insert/delete in middle. LinkedList uses
doubly-linked nodes — O(n) random access, O(1) insert/delete when node reference known. Use ArrayList for
frequent reads; LinkedList for frequent head/tail inserts.
Q: Explain the Java Memory Model and volatile keyword.
A: Ans: The JMM defines how threads interact through memory. Without volatile, each thread may cache a
variable locally. volatile guarantees visibility — writes by one thread are immediately visible to others. However,
volatile does NOT ensure atomicity (e.g., count++ is not atomic). Use AtomicInteger for atomic compound
operations.
Q: What is the difference between wait() and sleep()?
A: Ans: wait() is called on an Object, releases the monitor lock, and waits until notify()/notifyAll() is called — used
for inter-thread communication. sleep() is a static Thread method that pauses the thread for given ms without
releasing any lock. Both throw InterruptedException.
Q: What are the new features of Java 8?
A: Ans: Lambda expressions, Functional Interfaces (Predicate, Function, Consumer, Supplier), Stream API for
declarative collection processing, Optional for null-safety, Default/Static interface methods, new Date/Time API
([Link]), Method references, Nashorn JS engine.
Q: Explain how Generics work in Java.
A: Ans: Generics provide compile-time type safety and eliminate casts. They work via type erasure — the
compiler replaces type parameters with Object (or bounds) at compile time and inserts casts. At runtime, generic
type info is lost. Bounded wildcards: ? extends T (upper bound, read), ? super T (lower bound, write).
Q: What is the difference between Comparable and Comparator?
A: Ans: Comparable ([Link]) defines natural ordering via compareTo() — the class itself implements it (e.g.,
String, Integer). Comparator ([Link]) defines external custom ordering via compare() — useful when you can't
modify the class or need multiple sort orders. [Link](list, comparator) uses Comparator.
Q: What is method hiding vs method overriding?
A: Ans: Overriding applies to instance methods — resolved at runtime (dynamic dispatch). Hiding applies to
static methods — resolved at compile time based on reference type. If parent and child both have the same
static method, the one called depends on the reference type, not the actual object.
11. Infosys Interview Q&A; — SQL
In-depth answers for SQL & database questions

Q: What is the difference between WHERE and HAVING?


A: Ans: WHERE filters rows before grouping; cannot use aggregate functions. HAVING filters after GROUP BY;
can use aggregate functions (SUM, COUNT, AVG, etc.). Example: WHERE salary > 50000 vs HAVING
AVG(salary) > 50000.
Q: What are window functions? Give an example.
A: Ans: Window functions perform calculations across a set of rows related to the current row without collapsing
them (unlike GROUP BY). Common ones: ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), SUM()
OVER(), AVG() OVER(). Example: RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) ranks
employees within each department.
Q: Explain the difference between DELETE, TRUNCATE, and DROP.
A: Ans: DELETE removes specific rows (can use WHERE), logged row-by-row, can be rolled back, triggers fire.
TRUNCATE removes all rows, minimal logging, faster, cannot roll back in most DBs, resets identity. DROP
removes the entire table structure and data permanently.
Q: What is a primary key vs unique key vs foreign key?
A: Ans: Primary Key: uniquely identifies each row; cannot be NULL; only one per table. Unique Key: ensures
uniqueness; can have NULLs (typically one NULL allowed); multiple per table. Foreign Key: references PK of
another table; enforces referential integrity; can have duplicates and NULLs.
Q: What is a subquery? Types?
A: Ans: A subquery is a SELECT nested inside another query. Correlated subquery: references outer query
(re-executed for each outer row). Non-correlated: independent of outer query (executed once). Types by
position: in WHERE (filter), in FROM (derived table), in SELECT (scalar subquery).
Q: How do you optimize a slow SQL query?
A: Ans: (1) Use EXPLAIN/EXPLAIN ANALYZE to see query plan and identify full scans. (2) Add indexes on
WHERE, JOIN, ORDER BY columns. (3) Avoid SELECT * — select only needed columns. (4) Avoid functions
on indexed columns in WHERE (disables index use). (5) Optimize JOINs — join on indexed foreign keys. (6)
Use covering indexes. (7) Partition large tables. (8) Consider denormalization for read-heavy workloads.
Q: What are SQL aggregate functions?
A: Ans: COUNT(col) — number of non-null rows. SUM(col) — total. AVG(col) — average. MIN(col)/MAX(col) —
extremes. COUNT(*) counts all rows including NULLs. Used with GROUP BY; can be filtered with HAVING.
Q: What is the difference between UNION and UNION ALL?
A: Ans: UNION combines result sets and removes duplicates (slower — requires sort/hash). UNION ALL
includes duplicates and is faster. Use UNION ALL unless you specifically need distinct rows.
12. Quick Revision Cheatsheet
Last-minute revision for Infosys Java Developer Interview

Java Core
✓ String is immutable — stored in pool; use StringBuilder for mutation

✓ == for reference, equals() for content comparison

✓ final: variable=constant, method=no override, class=no extend

✓ static: class-level, no access to instance members

✓ abstract class vs interface: code reuse vs contract

Collections
✓ ArrayList: O(1) get, O(n) insert middle; backed by array

✓ HashMap: O(1) avg get/put; hash + equals must be consistent

✓ TreeMap/TreeSet: O(log n); sorted; null key not allowed

✓ ConcurrentHashMap: thread-safe; better than synchronized HashMap

✓ PriorityQueue: min-heap; O(log n) add/poll

Java 8
✓ Lambda: (params) -> expression / block

✓ Stream: filter, map, flatMap, reduce, collect, findFirst, anyMatch

✓ Optional: ofNullable, orElse, map, ifPresent, orElseThrow

✓ [Link](), [Link](), [Link]()

✓ Method reference: Class::method, obj::method, Class::new

Multithreading
✓ Thread states: NEW→RUNNABLE→RUNNING→BLOCKED/WAITING→TERMINATED

✓ synchronized: method or block; volatile: visibility only

✓ wait()/notify() vs sleep() — lock release vs no lock release

✓ ExecutorService: newFixedThreadPool, submit(), [Link]()

✓ Deadlock: lock ordering, tryLock; AtomicInteger for atomic ops

SQL
✓ INNER JOIN: matching rows both tables; LEFT JOIN: all left + matched right

✓ WHERE before GROUP BY; HAVING filters aggregates


✓ Index: clustered (PK order), non-clustered, composite (leftmost rule)

✓ ACID: Atomicity, Consistency, Isolation, Durability

✓ RANK() vs DENSE_RANK(): gaps vs no gaps after ties

✓ DELETE (row-by-row, rollback) vs TRUNCATE (all, fast, no rollback)

✓ Subquery types: correlated (outer ref) vs non-correlated

■ Infosys Interview Tips:


• Code on paper — practise writing clean code without IDE
• Explain your thought process aloud before and while coding
• Mention time & space complexity after every solution
• For Spring Boot / Microservices roles: know REST principles, @RestController, @Service, @Repository, JPA
repositories
• Be ready for HR questions: Why Infosys? Where do you see yourself in 5 years?
• Prepare 1-2 project examples using STAR method (Situation, Task, Action, Result)

Best of luck with your Infosys interview! ■

You might also like