0% found this document useful (0 votes)
2 views37 pages

Java FullStack Complete v3

The document outlines a comprehensive guide for preparing for Java Full Stack Developer interviews, detailing 18 phases covering various topics such as Core Java, Object-Oriented Programming, Advanced Java, and more. Each phase includes theoretical concepts and coding questions, with a total of over 800 questions designed to help candidates secure positions in top tech companies. It emphasizes the importance of modern Java features, DevOps practices, and system design principles in the interview process.

Uploaded by

soumyasingh43636
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)
2 views37 pages

Java FullStack Complete v3

The document outlines a comprehensive guide for preparing for Java Full Stack Developer interviews, detailing 18 phases covering various topics such as Core Java, Object-Oriented Programming, Advanced Java, and more. Each phase includes theoretical concepts and coding questions, with a total of over 800 questions designed to help candidates secure positions in top tech companies. It emphasizes the importance of modern Java features, DevOps practices, and system design principles in the interview process.

Uploaded by

soumyasingh43636
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

■ JAVA FULL STACK DEVELOPER

Complete Interview
(2026 Question
Edition) Bank — v3.0
18 Phases | Theory + Coding | 4 LPA → 12 LPA | 800+ Questions
Backend + Frontend + Security + DevOps + System Design + Modern Java 17/21
TCS · Infosys · Wipro · Accenture · Cognizant · HCL · Capgemini · Amazon · Flipkart · Paytm

# Phase Topics Qs

1 Core Java Fundamentals JVM, Types, Strings, Arrays, Methods 50+

2 Object-Oriented Programming 4 Pillars, Inheritance, Polymorphism 55+

3 Advanced Java & Collections Collections, Generics, Exceptions 50+

4 Java 8+ Modern Features Lambdas, Streams, Optional 45+

5 Multithreading & Concurrency Threads, Sync, Executor, CompletableFuture 45+

6 File Handling & I/O Streams, Serialization, NIO 25+

7 MySQL & SQL Joins, GroupBy, Window Functions, Indexes 50+

8 JDBC CRUD, PreparedStatement, Transactions, Pool 45+

9 HTML & CSS Semantic HTML, Box Model, Flexbox, Grid, RWD 40+

10 JavaScript (ES6+) DOM, Closures, Promises, Async/Await, Fetch 55+

11 React JS Hooks, Props, State, Router, Redux, Axios 50+

12 Web & API Fundamentals HTTP, REST, CORS, Cookies, JWT, OAuth2 35+

13 Spring Boot & REST API IoC, DI, REST, JPA, Validation, Testing 55+

14 Spring Security & JWT Auth, JWT, BCrypt, RBAC, OAuth2 30+

15 Modern Java 17 / 21 Records, Sealed Classes, Pattern Match, VThreads 25+

16 DSA + Design Patterns + SOLID Coding, Patterns, Principles 55+

17 DevOps & Deployment Git, Docker, CI/CD, AWS Basics 30+

18 System Design Basics Microservices, Caching, Kafka, Scaling 35+


■ PHASE 1 — Core Java Fundamentals

1.1 JVM · JDK · JRE


Q1. Difference between JDK, JRE, JVM?
Ans: JVM: executes bytecode, platform-specific. JRE = JVM + libraries (to run Java). JDK = JRE + compiler/tools (to
develop). WORA: Write Once Run Anywhere because bytecode is platform-neutral.
■ Asked in: TCS, Infosys, Wipro, Capgemini — all fresher rounds

Q2. What is JIT compiler?


Ans: Just-In-Time: part of JVM. Compiles frequently-executed bytecode to native machine code at runtime. Tiered:
interpreted → C1 → C2 compiler. Eliminates repeated interpretation overhead.

Q3. What is ClassLoader?


Ans: Loads .class files into JVM. Bootstrap (core classes) → Extension → Application. Delegation: child asks parent first
before loading itself.

1.2 Data Types & Strings


Q4. 8 primitive data types with sizes?
Ans: byte(1B), short(2B), int(4B), long(8B,suffix L), float(4B,suffix f), double(8B), char(2B,Unicode), boolean(1bit). All
others are reference types stored on Heap.

Q5. Autoboxing/unboxing pitfalls?


Ans: Integer cache only -128 to 127 (== works in range, fails outside). NPE when unboxing null Integer. Performance
overhead in hot loops.
Integer a=127,b=127; a==b; // true (cached)
Integer c=128,d=128; c==d; // false! — use .equals()

Q6. Why is String immutable?


Ans: Security (class loading, URLs, DB). String Pool efficiency (safe sharing). Thread safety. HashCode caching for
HashMap performance.

Q7. String vs StringBuilder vs StringBuffer?


Ans: String: immutable, creates new object on each concat — use only for few concats. StringBuilder: mutable, NOT
thread-safe, fastest — use in loops. StringBuffer: mutable, thread-safe (synchronized), slower.

Q8. [CODING] First non-repeating character.


char firstNonRepeat(String s){
LinkedHashMap<Character,Integer> m=new LinkedHashMap<>();
for(char c:[Link]()) [Link](c,1,Integer::sum);
for(var e:[Link]()) if([Link]()==1) return [Link]();
return '_';
}

Q9. [CODING] Check if two strings are anagrams.


boolean isAnagram(String a,String b){
char[] ca=[Link](),cb=[Link]();
[Link](ca); [Link](cb);
return [Link](ca,cb);
}

1.3 Arrays & Methods


Q10. [CODING] Second largest element.
int secondLargest(int[] a){
int max=Integer.MIN_VALUE,sec=Integer.MIN_VALUE;
for(int x:a){if(x>max){sec=max;max=x;}else if(x>sec&&x!=max)sec=x;}
return sec;
}

Q11. [CODING] Move zeros to end.


void moveZeros(int[] a){int p=0;for(int x:a)if(x!=0)a[p++]=x;while(p<[Link])a[p++]=0;}

Q12. Is Java pass-by-value?


Ans: Always. Primitives: copy of value. Objects: copy of reference — can mutate object state but cannot reassign the
original reference variable.

Q13. [CODING] Check palindrome number.


boolean isPalindromeNum(int n){if(n<0)return false;int o=n,r=0;while(n>0){r=r*10+n%10;n/=10;}return o==r;}

Q14. [CODING] Count vowels in string.


long countVowels(String s){return [Link]().chars().filter("aeiou"::indexOf).count();}
■ PHASE 2 — Object-Oriented Programming

2.1 Four Pillars


Q1. What are the 4 pillars of OOP?
Ans: Encapsulation: private fields + public getters/setters. Inheritance: child reuses parent (extends). Polymorphism:
overloading (compile-time) + overriding (runtime). Abstraction: abstract class + interface hides implementation.
■ Asked in EVERY Java interview — must know perfectly

Q2. Access modifiers?


Ans: private: same class. default: same package. protected: package + subclasses. public: everywhere.

2.2 Constructors & Keywords


Q3. Constructor types and chaining?
Ans: Default (compiler-provided if none written), Parameterized, Copy (manual). this(): chain within same class. super():
call parent constructor. Both must be first statement.

Q4. What is the this keyword?


Ans: Refers to current object. Uses: 1) Resolve name conflicts ([Link]=param). 2) Call another constructor (this()). 3)
Pass current object. 4) Method chaining (return this).

2.3 Inheritance & Polymorphism


Q5. Why no multiple inheritance with classes?
Ans: Diamond Problem — ambiguity when two parents have same method. Solved via interfaces: implementing class
must override conflicting default methods explicitly.

Q6. Method overriding rules?


Ans: Same name + same params. Return: same or covariant subtype. Access: same or wider. Cannot override: final,
static, private. Use @Override always.

Q7. Abstract class vs Interface — full comparison?


Ans: Abstract: single inheritance, constructors allowed, instance fields, any access modifier, IS-A. Interface: multiple
implementation, no constructors, static final fields only, public by default, CAN-DO. Java 8+: interfaces have default+static
methods.
■ #1 most asked OOP question

Q8. Runtime polymorphism — how JVM handles it?


Ans: JVM maintains vtable per class. At runtime, looks up actual object's vtable (not reference type). Core of dynamic
dispatch.

2.4 OOP Coding


Q9. [CODING] Thread-safe Singleton.
public enum Singleton{INSTANCE; public void work(){}}
// Or double-checked locking:
private static volatile Singleton inst;
public static Singleton get(){
if(inst==null){synchronized([Link]){if(inst==null)inst=new Singleton();}}
return inst;
}

Q10. [CODING] Builder pattern.


class User{
private final String name,email; private final int age;
private User(Builder b){name=[Link];email=[Link];age=[Link];}
static class Builder{
String name,email; int age;
Builder name(String n){name=n;return this;}
Builder email(String e){email=e;return this;}
Builder age(int a){age=a;return this;}
User build(){return new User(this);}
}
}
■ PHASE 3 — Advanced Java & Collections

3.1 Exception Handling


Q1. Checked vs unchecked exceptions?
Ans: Checked: must declare/handle at compile time (IOException, SQLException). Unchecked: extend
RuntimeException, compiler doesn't enforce (NPE, IllegalArgumentException, ClassCastException).

Q2. try-with-resources?
Ans: Java 7. Resources in try() auto-closed (must implement AutoCloseable). Closed in reverse order. Replaces finally
for resource cleanup.

Q3. throw vs throws?


Ans: throw: inside method body, throws exception object. throws: in method signature, declares possible exceptions.

Q4. [CODING] Custom exception.


class InsufficientFundsException extends RuntimeException{
private final double shortfall;
InsufficientFundsException(double amt,double bal){
super([Link]("Need %.2f more",amt-bal)); shortfall=amt-bal;}
double getShortfall(){return shortfall;}
}

3.2 Collections Framework


Q5. HashMap internal working?
Ans: Node[] bucket array, capacity 16, load factor 0.75. put(k,v): hash → index → if empty insert; collision → linked list
(equals()). Java 8: list → red-black tree when bucket>8. Resize: size>cap*0.75 → double + rehash.
■ Top asked — Amazon, Flipkart, Paytm, Goldman Sachs

Q6. HashMap vs LinkedHashMap vs TreeMap?


Ans: HashMap: no order O(1). LinkedHashMap: insertion order O(1). TreeMap: sorted O(log n). Use LinkedHashMap for
LRU; TreeMap for sorted map.

Q7. fail-fast vs fail-safe?


Ans: Fail-fast: ConcurrentModificationException if modified during iteration (ArrayList, HashMap). Fail-safe: works on
copy (CopyOnWriteArrayList, ConcurrentHashMap).

Q8. equals() and hashCode() contract?


Ans: If [Link](b) then [Link]()==[Link]() MUST be true. Never override one without other.

Q9. [CODING] LRU Cache.


class LRUCache<K,V> extends LinkedHashMap<K,V>{
final int cap;
LRUCache(int c){super(c,0.75f,true);cap=c;}
protected boolean removeEldestEntry([Link]<K,V> e){return size()>cap;}
}

3.3 Generics
Q10. PECS rule?
Ans: Producer Extends Consumer Super. <? extends T>: read from. <? super T>: write to.
■ PHASE 4 — Java 8+ Modern Features

4.1 Lambda & Functional Interfaces


Q1. What is a lambda expression?
Ans: Anonymous function. Syntax: (params)->expression. Only where functional interface expected. Captures
effectively-final local variables.

Q2. Built-in functional interfaces?


Ans: Predicate<T>: T→boolean. Function<T,R>: T→R. Consumer<T>: T→void. Supplier<T>: ()→T. UnaryOperator<T>:
T→T. BinaryOperator<T>: T,T→T.

4.2 Stream API


Q3. Stream API — characteristics?
Ans: Does NOT store data. Lazy (intermediate ops run only when terminal called). Functional (no mutation). Single-use
only. Sequential or parallel.
■ Asked in 90%+ interviews above 6 LPA

Q4. map() vs flatMap()?


Ans: map(): one-to-one. flatMap(): one-to-many, flattens nested streams into single stream.

Q5. [CODING] Average salary by department.


Map<String,Double> avg=[Link]()
.collect([Link](Employee::getDept,
[Link](Employee::getSalary)));

Q6. [CODING] Find duplicates using streams.


Set<Integer> seen=new HashSet<>();
List<Integer> dups=[Link]().filter(n->![Link](n)).collect(toList());

Q7. [CODING] 3rd highest salary.


Optional<Double> third=[Link]()
.map(Employee::getSalary).distinct()
.sorted([Link]()).skip(2).findFirst();

4.3 Optional & Method References


Q8. What is Optional?
Ans: Container that may/may not hold value. Avoids NPE. Key: of(), ofNullable(), orElse(), orElseGet(), orElseThrow(),
map(), filter(), ifPresent().

Q9. Four types of method references?


Ans: Static: Integer::parseInt. Instance of object: prefix::concat. Instance of type: String::toUpperCase. Constructor:
ArrayList::new.
■ PHASE 5 — Multithreading & Concurrency

5.1 Thread Basics


Q1. Ways to create a thread?
Ans: 1) Extend Thread. 2) Implement Runnable (preferred). 3) Callable+Future. 4) Lambda. 5) ExecutorService. Prefer
Runnable/Callable — avoids single inheritance limit.

Q2. Thread lifecycle states?


Ans: NEW→RUNNABLE→RUNNING→BLOCKED/WAITING/TIMED_WAITING→TERMINATED.

Q3. sleep() vs wait()?


Ans: sleep(): Thread method, holds lock, pauses duration, auto-resumes. wait(): Object method, RELEASES lock, needs
notify()/notifyAll() to resume, must be in synchronized block.

5.2 Synchronization
Q4. volatile vs synchronized?
Ans: volatile: visibility only, no atomicity, no locking. synchronized: visibility + atomicity + locking. For simple flags: volatile.
For compound ops (check-then-act): synchronized or AtomicInteger.

Q5. What is deadlock? Prevention?


Ans: Threads waiting for each other's locks forever. Prevention: always acquire locks in same order, tryLock() with
timeout, avoid nested locks.

Q6. ReentrantLock advantages?


Ans: tryLock() (non-blocking), lockInterruptibly(), fair locking, Condition variables. Must unlock in finally block always.

5.3 Executor & Async


Q7. Thread pool types?
Ans: newFixedThreadPool(n): fixed threads. newCachedThreadPool(): unlimited, reuses idle.
newSingleThreadExecutor(): 1 sequential. newScheduledThreadPool(n): scheduled tasks.

Q8. What is CompletableFuture?


Ans: Async programming (Java 8). Chain: thenApply (transform), thenAccept (consume), thenCompose (chain). Error:
exceptionally(), handle(). Combine: allOf(), anyOf().
[Link](()->fetchUser(id))
.thenApply(u->enrichProfile(u))
.thenAccept([Link]::println)
.exceptionally(e->{[Link]("Err:"+e);return null;});

Q9. [CODING] Producer-Consumer with BlockingQueue.


BlockingQueue<Integer> q=new LinkedBlockingQueue<>(10);
new Thread(()->{for(int i=0;i<20;i++)try{[Link](i);}catch(InterruptedException e){break;}}).start();
new Thread(()->{while(true)try{[Link]([Link]());}catch(InterruptedException e){break;}}).start
();
■ PHASE 6 — File Handling & I/O

6.1 I/O Streams


Q1. Byte stream vs Character stream?
Ans: Byte (InputStream/OutputStream): raw bytes, binary files. Character (Reader/Writer): chars with encoding, text files.

Q2. Read file efficiently?


[Link]([Link]("[Link]")).filter(l->![Link]()).forEach([Link]::println);
List<String> lines=[Link]([Link]("[Link]"));

Q3. Serialization + transient keyword?


Ans: Serialization: object→byte stream (implements Serializable). transient: field excluded from serialization.
serialVersionUID: declare explicitly to avoid InvalidClassException on class change.
class User implements Serializable{
static final long serialVersionUID=1L;
String name;
transient String password; // not serialized
}
■■ PHASE 7 — MySQL & SQL

7.1 SQL Basics


Q1. DDL vs DML vs DCL vs TCL?
Ans: DDL: CREATE, ALTER, DROP, TRUNCATE (structure). DML: SELECT, INSERT, UPDATE, DELETE (data). DCL:
GRANT, REVOKE (permissions). TCL: COMMIT, ROLLBACK, SAVEPOINT (transactions).
■ Asked in TCS, Infosys, Wipro, Capgemini backend rounds

Q2. DELETE vs TRUNCATE vs DROP?


Ans: DELETE: DML, specific rows, can rollback, triggers fire, slow. TRUNCATE: DDL, all rows, no rollback, no triggers,
fast. DROP: removes entire table permanently.

Q3. WHERE vs HAVING?


Ans: WHERE: filters rows BEFORE grouping (cannot use aggregates). HAVING: filters AFTER GROUP BY (can use
COUNT, SUM, AVG).
SELECT dept, AVG(salary) avg_sal FROM employees
WHERE salary>20000 GROUP BY dept HAVING AVG(salary)>50000;

7.2 Joins
Q4. Types of JOINs?
Ans: INNER: rows matching in BOTH. LEFT: all left + matching right (NULL if no match). RIGHT: all right + matching left.
FULL OUTER: all rows both sides. CROSS: cartesian product. SELF: table joined with itself.

Q5. [SQL] Find employees without a department.


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

Q6. [SQL] Employee and their manager (SELF JOIN).


SELECT [Link] employee, [Link] manager
FROM employees e LEFT JOIN employees m ON e.manager_id=[Link];

7.3 Aggregates & Window Functions


Q7. [SQL] Second highest salary.
-- Method 1
SELECT MAX(salary) FROM employees WHERE salary<(SELECT MAX(salary) FROM employees);
-- Method 2: DENSE_RANK (works for Nth highest)
SELECT salary FROM(SELECT salary,DENSE_RANK()OVER(ORDER BY salary DESC)r FROM employees)t WHERE r=2;
■ Most common SQL question — asked in ALL companies

Q8. RANK vs DENSE_RANK vs ROW_NUMBER?


Ans: ROW_NUMBER(): unique sequential (1,2,3,4). RANK(): gaps after ties (1,2,2,4). DENSE_RANK(): no gaps
(1,2,2,3). Use DENSE_RANK for Nth highest salary.

Q9. [SQL] Top 3 salaries per department.


SELECT name,salary,dept FROM(
SELECT name,salary,dept,DENSE_RANK()OVER(PARTITION BY dept ORDER BY salary DESC)r
FROM employees)t WHERE r<=3;

Q10. [SQL] Find duplicate emails.


SELECT email,COUNT(*)cnt FROM users GROUP BY email HAVING COUNT(*)>1;

7.4 Indexes & Transactions


Q11. What is an Index?
Ans: B-Tree structure for faster lookup at cost of storage/write speed. Create on: WHERE, JOIN, ORDER BY columns.
Clustered (Primary Key, data sorted) vs Non-clustered (separate pointer structure, multiple allowed).

Q12. ACID properties?


Ans: Atomicity: all or nothing. Consistency: valid state before/after. Isolation: concurrent transactions don't interfere.
Durability: committed data survives crash.

Q13. Transaction isolation levels?


Ans: READ UNCOMMITTED (dirty reads). READ COMMITTED (no dirty reads). REPEATABLE READ (MySQL default,
no phantom rows in simple reads). SERIALIZABLE (full isolation, slowest).
■ PHASE 8 — JDBC

8.1 JDBC Basics


Q1. What is JDBC? Why important?
Ans: Java API for relational database interaction. Standard interface — same code for MySQL/Oracle/PostgreSQL (just
change driver). Foundation JPA/Hibernate builds on. Type 4 driver (pure Java, most used) is correct answer.
■ Asked in TCS, Infosys, Wipro, Cognizant backend rounds

Q2. JDBC connection steps?


Ans: 1) Load driver (auto Java 6+). 2) [Link](). 3) Create PreparedStatement. 4) Execute. 5)
Process ResultSet. 6) Close (try-with-resources).

Q3. Statement vs PreparedStatement vs CallableStatement?


Ans: Statement: no params, vulnerable to SQL injection, compiled each time. PreparedStatement: parameterized,
pre-compiled, SQL injection safe — ALWAYS USE. CallableStatement: stored procedures.
■ PreparedStatement vs Statement very frequently asked

Q4. What is SQL Injection? How PreparedStatement prevents it?


Ans: Attacker injects SQL via user input. PreparedStatement sends SQL and params separately — DB treats params as
data, never as code.
// VULNERABLE
"SELECT * FROM users WHERE name='"+name+"'"; // name="' OR '1'='1" → login bypass!
// SAFE
PreparedStatement ps=[Link]("SELECT * FROM users WHERE name=?");
[Link](1,name); // sanitized automatically

8.2 JDBC CRUD


Q5. [CODING] Insert with generated key.
PreparedStatement ps=[Link](
"INSERT INTO employees(name,salary)VALUES(?,?)",Statement.RETURN_GENERATED_KEYS);
[Link](1,"Alice"); [Link](2,75000);
[Link]();
ResultSet keys=[Link]();
if([Link]()) [Link]("New ID:"+[Link](1));

Q6. execute() vs executeQuery() vs executeUpdate()?


Ans: executeQuery(): SELECT → returns ResultSet. executeUpdate(): INSERT/UPDATE/DELETE → returns int (rows
affected). execute(): any SQL → boolean.

8.3 Transactions & Connection Pool


Q7. [CODING] JDBC Transaction with rollback.
[Link](false);
try{
[Link](); // debit
[Link](); // credit
[Link]();
}catch(SQLException e){[Link]();throw e;}
finally{[Link](true);}

Q8. What is Connection Pooling? HikariCP?


Ans: DB connections are expensive (100-500ms each). Pool pre-creates and reuses connections. HikariCP: fastest Java
pool, default in Spring Boot. Key configs: maximumPoolSize(10), connectionTimeout, idleTimeout, maxLifetime.

Q9. JDBC vs Hibernate vs Spring Data JPA?


Ans: JDBC: full SQL control, max performance. Hibernate: ORM, less SQL. Spring Data JPA: rapid dev, auto-generated
repositories. Rule: Spring Data JPA for most → JDBC for performance-critical native queries.
■ PHASE 9 — HTML & CSS

9.1 HTML5
Q1. What are semantic HTML5 tags? Why use them?
Ans: Tags that convey meaning: <header>, <nav>, <main>, <section>, <article>, <aside>, <footer>, <figure>,
<figcaption>. Benefits: SEO (search engines understand structure), Accessibility (screen readers), Readability
(self-documenting code). Non-semantic: <div>, <span> (no meaning).
■ Asked in: Wipro, HCL, Capgemini frontend rounds

Q2. What is the difference between block and inline elements?


Ans: Block: takes full width, starts new line, can set width/height (div, p, h1-h6, ul, li, section). Inline: only takes content
width, no new line, cannot set width/height (span, a, strong, em, img). Inline-block: like inline but can set width/height.

Q3. What is the difference between <script>, <link>, and <style>?


Ans: <link rel='stylesheet'> — external CSS (in <head>). <style> — inline CSS block (in <head>). <script> — JavaScript
(end of <body> or with defer/async). defer: execute after HTML parsed. async: execute as soon as loaded (may block
parse).

Q4. What are HTML5 form input types?


Ans: text, password, email, number, tel, url, date, time, datetime-local, range, color, file, checkbox, radio, submit, reset.
HTML5 adds built-in validation (required, min, max, pattern, minlength).
<form action="/submit" method="POST">
<input type="email" placeholder="Email" required>
<input type="password" minlength="8" required>
<input type="number" min="18" max="100">
<button type="submit">Submit</button>
</form>

Q5. What is the difference between id and class attributes?


Ans: id: unique per page, used for specific element targeting (#id in CSS, getElementById in JS). class: reusable across
multiple elements (.class in CSS, getElementsByClassName in JS). id has higher CSS specificity.

Q6. What are data attributes?


Ans: Custom attributes: data-* for storing extra data on HTML elements. Access in JS: [Link].
<button data-user-id="42" data-role="admin">Edit</button>
// JS: [Link] // "42", [Link] // "admin"

Q7. What is the difference between localStorage, sessionStorage, and cookies?


Ans: localStorage: persists until manually cleared, 5-10MB, accessible by JS, no expiry. sessionStorage: cleared when
tab closed, 5-10MB, JS only. Cookies: sent with every HTTP request (security risk), 4KB max, can have expiry, can be
httpOnly (no JS access, XSS protection).
■ Asked in: Accenture, Cognizant, TCS Digital

9.2 CSS Fundamentals


Q8. What is the CSS Box Model?
Ans: Every element is a box: Content → Padding → Border → Margin. box-sizing: content-box (default — width excludes
padding/border). box-sizing: border-box (width includes padding+border — easier to work with, always use this).
* { box-sizing: border-box; } /* Always add this globally */
.box { width:300px; padding:20px; border:2px solid; margin:10px; }
/* content-box: total width = 300+20+20+2+2 = 344px */
/* border-box: total width = 300px (padding+border inside) */

Q9. What is CSS Specificity? Order of priority?


Ans: How browsers decide which CSS rule applies. Specificity order (lowest to highest): * (0) → element/pseudo-element
(1) → class/attribute/pseudo-class (10) → id (100) → inline style (1000) → !important (override all, avoid). When equal
specificity: last rule wins.
Q10. What is the difference between position: relative, absolute, fixed, sticky?
Ans: relative: positioned relative to its normal position, takes up space. absolute: removed from flow, positioned relative to
nearest non-static parent. fixed: positioned relative to viewport (stays on scroll). sticky: behaves like relative until scroll
threshold, then fixed.

Q11. What is Flexbox? Key properties?


Ans: 1D layout system (row or column). Container: display:flex, flex-direction, justify-content (main axis), align-items
(cross axis), flex-wrap, gap. Items: flex-grow, flex-shrink, flex-basis, align-self, order.
/* Center anything with Flexbox */
.container {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
gap: 16px;
}
.item { flex: 1; } /* each item takes equal space */

Q12. What is CSS Grid? When to use Grid vs Flexbox?


Ans: 2D layout system (rows AND columns). Use Grid for: page layouts, complex 2D structures. Use Flexbox for: 1D
layouts, centering, nav bars, card rows. They complement each other — Grid for outer layout, Flexbox for inner
components.
/* 3-column responsive grid */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 24px;
}

Q13. What are CSS Media Queries? Mobile-first approach?


Ans: Apply styles based on screen size/device. Mobile-first: write CSS for mobile first, then override for larger screens
using min-width. (Desktop-first uses max-width — harder to maintain).
/* Mobile-first */
.card { width: 100%; } /* mobile default */
@media (min-width: 768px) { /* tablet+ */
.card { width: 50%; }
}
@media (min-width: 1024px) { /* desktop+ */
.card { width: 33.33%; }
}

Q14. What is the difference between em, rem, px, vh, vw?
Ans: px: fixed pixels. em: relative to parent font-size (compounds — can be unpredictable). rem: relative to root (html)
font-size (consistent — preferred for font sizes). vh: 1% of viewport height. vw: 1% of viewport width. Use rem for fonts, px
for borders, % or fr for widths.

Q15. What is CSS Specificity conflict? How to fix without !important?


Ans: Add more specific selector instead of !important. Better: use BEM naming (.block__element--modifier), keep
specificity flat, use CSS custom properties (variables). !important creates maintenance nightmares — avoid.

Q16. What are CSS Custom Properties (Variables)?


:root {
--primary-color: #1a56db;
--font-size-base: 16px;
--spacing-md: 16px;
}
.btn { background: var(--primary-color); padding: var(--spacing-md); }
.btn:hover { background: color-mix(in srgb, var(--primary-color) 80%, black); }
■ PHASE 10 — JavaScript (ES6+)

10.1 JS Fundamentals
Q1. var vs let vs const?
Ans: var: function-scoped, hoisted (initialized as undefined), can re-declare. let: block-scoped, hoisted but NOT initialized
(TDZ — ReferenceError if accessed before declaration), no re-declare. const: block-scoped, must initialize at declaration,
cannot reassign (but object properties can change).
[Link](x); // undefined (var hoisted)
var x=5;
[Link](y); // ReferenceError (let TDZ)
let y=5;
const arr=[1,2,3];
[Link](4); // OK - mutating object
arr=[]; // TypeError - cannot reassign const
■ var/let/const TDZ is asked in almost every JS interview

Q2. What is hoisting in JavaScript?


Ans: Variable and function declarations moved to top of scope during compilation. var declarations hoisted + initialized as
undefined. Function declarations fully hoisted (can call before declaration). let/const hoisted but NOT initialized (Temporal
Dead Zone). Function expressions NOT hoisted.

Q3. What is the difference between == and === in JavaScript?


Ans: == (loose equality): type coercion happens before comparison. === (strict equality): no coercion, checks value AND
type. Always use === to avoid unexpected behavior.
0 == false // true (type coercion)
0 === false // false (different types)
null == undefined // true
null === undefined // false
"" == false // true — CONFUSING, always use ===!

Q4. What are JavaScript data types?


Ans: Primitives (7): string, number, boolean, null, undefined, symbol, bigint. Reference: object (plain objects, arrays,
functions). typeof null === 'object' (historical bug in JS).

10.2 Functions & Scope


Q5. What is a closure?
Ans: Function that remembers variables from its outer scope even after outer function has returned. Created every time a
function is created inside another function.
function counter(){
let count=0;
return{
increment:()=>++count,
decrement:()=>--count,
value:()=>count
};
}
const c=counter();
[Link](); [Link]();
[Link]([Link]()); // 2 — count is 'closed over'
■ Closure is asked in almost every JS interview — must know deeply

Q6. What is 'this' in JavaScript?


Ans: Refers to execution context. In object method: the object. In regular function: global (window) in non-strict, undefined
in strict mode. In arrow function: inherits 'this' from lexical scope (doesn't have own 'this'). In event listener: the element.
call/apply/bind can set 'this' explicitly.
const obj={name:'Alice',
greet:function(){[Link]([Link]);}, // 'Alice'
greetArrow:()=>[Link]([Link]) // undefined (lexical)
};

Q7. What is the difference between call, apply, and bind?


Ans: call(thisArg, arg1, arg2): invoke immediately with given this and args. apply(thisArg, [args]): invoke immediately,
args as array. bind(thisArg, arg1): returns NEW function with this bound, doesn't invoke immediately. Use bind for event
handlers and partial application.

Q8. Arrow function vs regular function?


Ans: Arrow: no own 'this' (lexical), no arguments object, cannot be used as constructor (no new), no prototype property,
shorter syntax. Regular: own 'this', has arguments, can be constructor. Use arrow for callbacks and when you need outer
'this'.

10.3 Async JavaScript


Q9. What is the Event Loop?
Ans: JS is single-threaded. Call stack runs synchronous code. Web APIs handle async (setTimeout, fetch). Callback
queue holds callbacks ready to run. Event loop: if call stack empty → take from callback queue → put on stack. Microtask
queue (Promises) has HIGHER priority than callback queue (setTimeout).
[Link]('1');
setTimeout(()=>[Link]('2'),0);
[Link]().then(()=>[Link]('3'));
[Link]('4');
// Output: 1, 4, 3, 2 (Promise microtask before setTimeout)
■ Event loop asked in product company interviews — Swiggy, Razorpay, Zepto

Q10. What is a Promise? States?


Ans: Object representing eventual completion/failure of async op. States: pending (initial), fulfilled (success, .then() runs),
rejected (failure, .catch() runs). Immutable once settled. Chainable with .then().catch().finally().
const promise=new Promise((resolve,reject)=>{
setTimeout(()=>resolve('Done!'),1000);
});
[Link](result=>[Link](result)).catch(err=>[Link](err));

Q11. async/await vs Promises?


Ans: async/await is syntactic sugar over Promises — same underlying mechanism. async function always returns a
Promise. await pauses execution until Promise resolves. Use try/catch for error handling. Makes async code look
synchronous — more readable.
// Promise chaining
fetch('/api/user').then(r=>[Link]()).then(user=>[Link](user)).catch([Link]);
// async/await (cleaner)
async function getUser(){
try{
const res=await fetch('/api/user');
const user=await [Link]();
[Link](user);
}catch(err){[Link](err);}
}

Q12. [Link] vs [Link] vs [Link]?


Ans: [Link]([p1,p2]): runs in parallel, resolves when ALL resolve, rejects if ANY rejects (fail-fast).
[Link]([p1,p2]): resolves/rejects with FIRST settled. [Link]([p1,p2]): waits for ALL, returns array of
{status, value/reason} — never rejects. [Link]([p1,p2]): resolves with first FULFILLED (ignores rejections).

10.4 DOM & Events


Q13. DOM manipulation — key methods?
// Select
[Link]('id')
[Link]('.class') // first match
[Link]('div') // NodeList
// Create & modify
const el=[Link]('div');
[Link]='Hello'; [Link]('card');
[Link]('data-id','42');
[Link](el);
[Link]();
// Modify existing
[Link]='<strong>Hi</strong>'; // XSS risk!
[Link]='Safe text'; // safe

Q14. What is event delegation?


Ans: Instead of adding listener to each child, add ONE listener to parent. Uses event bubbling — events propagate up
DOM. More efficient (fewer listeners), works for dynamically added elements.
// Instead of: [Link](item=>[Link]('click',handler));
[Link]('list').addEventListener('click',(e)=>{
if([Link]('.item')) handleClick([Link]);
});

Q15. What is event bubbling vs capturing?


Ans: Bubbling (default): event fires on target, then bubbles UP to ancestors. Capturing: event fires top-down from
document to target. addEventListener(event, handler, true) for capturing. [Link]() stops bubbling.
[Link]() stops default browser action.

10.5 ES6+ Features


Q16. Destructuring, spread, rest?
// Destructuring
const {name,age=25}=user; // object (with default)
const [first,,third]=arr; // array (skip index 1)
const {address:{city}}=user; // nested
// Spread
const merged={...obj1,...obj2}; // merge objects
const copy=[...arr1,...arr2]; // merge arrays
// Rest
function sum(...nums){return [Link]((a,b)=>a+b,0);}

Q17. What are JavaScript modules (ES6)?


Ans: import/export for code splitting. Named exports: export const fn=()=>{}. Default export: export default class App.
Import: import {fn} from './module'. import App from './App'. Modules are strict mode by default, have own scope.

Q18. [CODING] Debounce function.


function debounce(fn,delay){
let timer;
return function(...args){
clearTimeout(timer);
timer=setTimeout(()=>[Link](this,args),delay);
};
}
// Usage: search input
[Link]('input',debounce(search,300));

Q19. [CODING] Deep clone an object.


// Simple (no functions/dates/undefined)
const clone=[Link]([Link](obj));
// Modern
const clone=structuredClone(obj); // JavaScript 2022, handles more types
// Manual recursive
function deepClone(obj){
if(obj===null||typeof obj!=='object') return obj;
if([Link](obj)) return [Link](deepClone);
return [Link]([Link](obj).map(([k,v])=>[k,deepClone(v)]));
}
■■ PHASE 11 — React JS

11.1 React Fundamentals


Q1. What is React? Key concepts?
Ans: UI library by Meta for building component-based UIs. Key: Virtual DOM (lightweight copy of real DOM, diffs changes
for efficient updates), Components (reusable UI pieces), JSX (HTML-like syntax in JS), Unidirectional data flow
(parent→child via props), Hooks (state + lifecycle in functions).
■ React is asked in all full-stack Java roles — Infosys, TCS Digital, Wipro VLSI

Q2. What is Virtual DOM? How does reconciliation work?


Ans: Lightweight JS object copy of real DOM. When state changes: 1) New virtual DOM created. 2) Diffing algorithm
compares old vs new (O(n) heuristic). 3) Only CHANGED nodes updated in real DOM (patching). Faster than directly
updating real DOM for frequent changes. React 18 uses concurrent rendering with Fiber.

Q3. JSX — what is it? How does it compile?


Ans: JavaScript XML — HTML-like syntax in JS. Babel compiles JSX to [Link]() calls. Rules: one root
element (use Fragment <> </> to avoid extra div), className not class, htmlFor not for, camelCase attributes, all tags
self-close.
// JSX
const el=<div className="card"><h1>{title}</h1></div>;
// Compiled to:
const el=[Link]('div',{className:'card'},[Link]('h1',null,title));

Q4. Props vs State?


Ans: Props: data passed FROM parent to child, READ-ONLY in child, changes cause re-render. State: data managed
INSIDE component, can change (useState), changes cause re-render. Rule: lift state up when siblings need same data.

11.2 React Hooks


Q5. What is useState?
Ans: Hook to add state to functional components. Returns [currentValue, setterFunction]. Setting state triggers re-render.
State updates are ASYNCHRONOUS (batched). Use functional update when new state depends on old.
const [count,setCount]=useState(0);
const [user,setUser]=useState({name:'',email:''});
// Functional update (when new state depends on old)
setCount(prev=>prev+1); // safe in async scenarios
// Update nested object
setUser(prev=>({...prev,name:'Alice'}));

Q6. What is useEffect? Dependency array?


Ans: Runs side effects after render. No deps: runs after EVERY render. Empty []: runs once after mount. [dep1,dep2]:
runs when deps change. Return cleanup function to prevent memory leaks.
useEffect(()=>{
const sub=subscribe(userId); // setup
return ()=>[Link](); // cleanup on unmount or userId change
},[userId]);
useEffect(()=>{ fetchData(); },[]); // once on mount
useEffect(()=>{ [Link]=count; }); // every render

Q7. What is useContext?


Ans: Avoids prop drilling — provides data to any nested component without passing through intermediate components.
Create context → Provider wraps tree → useContext reads value anywhere inside.
const ThemeCtx=createContext('light');
function App(){return <[Link] value="dark"><Child/></[Link]>}
function Child(){const theme=useContext(ThemeCtx); return <div className={theme}/>}
Q8. What is useReducer? When to use over useState?
Ans: Alternative to useState for complex state logic. Use when: state has multiple sub-values, next state depends on
previous state, complex transitions. Similar to Redux pattern but local.
function reducer(state,action){
switch([Link]){
case 'increment': return{...state,count:[Link]+1};
case 'reset': return{count:0};
default: return state;
}
}
const [state,dispatch]=useReducer(reducer,{count:0});
dispatch({type:'increment'});

Q9. What is useMemo and useCallback?


Ans: useMemo: memoizes expensive COMPUTED VALUE, recalculates only when deps change. useCallback:
memoizes FUNCTION reference, prevents child re-renders (with [Link]). Don't over-use — premature optimization.
// useMemo - expensive calculation
const sortedList=useMemo(()=>[Link](compareFn),[items]);
// useCallback - stable function reference for child
const handleClick=useCallback(()=>doSomething(id),[id]);

Q10. What is useRef?


Ans: Creates mutable ref that persists across renders WITHOUT causing re-render. Uses: 1) Access DOM element
directly (focus, scroll). 2) Store previous value. 3) Store any mutable value that doesn't need re-render.
const inputRef=useRef(null);
const handleFocus=()=>[Link]();
return <input ref={inputRef}/>;

11.3 React Patterns & Performance


Q11. What is [Link]?
Ans: HOC that prevents functional component re-render if props haven't changed. Shallow comparison by default.
Provide custom comparator as 2nd argument for deep comparison.

Q12. What is prop drilling? How to solve?


Ans: Passing props through many intermediate components just to reach deep child. Solutions: 1) Context API
(useContext). 2) State management (Redux, Zustand). 3) Component composition. 4) Custom hooks.

Q13. React Router — key concepts?


Ans: Client-side routing. Key: BrowserRouter (context), Routes+Route (path matching), Link (navigation without reload),
useNavigate (programmatic navigation), useParams (URL params), useSearchParams (query string), Outlet (nested
routes).
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/users/:id" element={<UserDetail/>}/>
<Route path="/admin" element={<ProtectedRoute><Admin/></ProtectedRoute>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
// In component:
const {id}=useParams();
const navigate=useNavigate();
navigate('/users/'+id);

Q14. API calls in React — fetch vs Axios?


Ans: fetch: built-in browser API. Does NOT reject on HTTP errors (404, 500) — must check [Link]. Returns
Response object, need .json(). Axios: library, rejects on HTTP errors, auto JSON parse, interceptors, request cancellation,
better error handling. Use Axios for production.
// Axios in React
useEffect(()=>{
const controller=new AbortController();
[Link]('/api/users',{signal:[Link]})
.then(res=>setUsers([Link]))
.catch(err=>{ if(![Link](err)) setError([Link]); });
return ()=>[Link](); // cancel on unmount
},[]);

Q15. What is Redux? When to use?


Ans: Predictable state container. Three principles: single source of truth (one store), state read-only (only actions can
change), changes via pure reducers. Use when: state shared across many components, complex state logic. Modern:
Redux Toolkit (RTK) reduces boilerplate significantly.
// Redux Toolkit slice
const counterSlice=createSlice({
name:'counter', initialState:{value:0},
reducers:{
increment:state=>{[Link]+=1;}, // Immer allows mutation
decrement:state=>{[Link]-=1;},
add:(state,action)=>{[Link]+=[Link];}
}
});
export const{increment,decrement,add}=[Link];
■ PHASE 12 — Web & API Fundamentals

12.1 HTTP & REST


Q1. What happens when you type a URL in browser?
Ans: 1) DNS lookup (domain→IP). 2) TCP connection (3-way handshake). 3) TLS handshake (for HTTPS). 4) HTTP
request sent. 5) Server processes, sends HTTP response. 6) Browser parses HTML, loads CSS/JS/images. 7) DOM built,
JS executed, page rendered.
■ Asked in product company interviews — Swiggy, Zepto, Razorpay

Q2. HTTP vs HTTPS?


Ans: HTTP: plain text, no encryption, port 80. HTTPS: HTTP + TLS/SSL encryption, port 443. HTTPS: data encrypted in
transit (confidentiality), server authenticated (certificate), data integrity. Mixed content: HTTPS page loading HTTP
resource — browser blocks it.

Q3. HTTP methods and when to use?


Ans: GET: retrieve resource (safe, idempotent, cacheable). POST: create resource (not idempotent, has body). PUT:
replace entire resource (idempotent). PATCH: partial update. DELETE: remove resource (idempotent). HEAD: GET but
no body (check if resource exists). OPTIONS: list allowed methods (CORS preflight).

Q4. What are REST principles?


Ans: 1) Client-Server separation. 2) Stateless (server stores no session). 3) Cacheable (define cache headers). 4)
Uniform Interface (standard HTTP verbs + resource URLs). 5) Layered System. 6) Code on Demand (optional). REST !=
just HTTP — must follow all constraints.

Q5. What is CORS? How to fix it?


Ans: Cross-Origin Resource Sharing: browser security policy preventing JS from making requests to different origin
(protocol+domain+port). Browser sends OPTIONS preflight first. Fix: server adds headers: Access-Control-Allow-Origin,
Access-Control-Allow-Methods, Access-Control-Allow-Headers.
// Spring Boot CORS fix
@CrossOrigin(origins="[Link]
@RestController class MyController{}
// Or globally:
@Bean CorsConfigurationSource corsConfig(){
CorsConfiguration c=new CorsConfiguration();
[Link]([Link]("[Link]
[Link]([Link]("GET","POST","PUT","DELETE"));
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
[Link]("/**",c); return source;
}

12.2 Authentication & Authorization


Q6. Authentication vs Authorization?
Ans: Authentication: WHO are you? (verify identity — login with username/password). Authorization: WHAT can you do?
(access control — can you access this resource?). AuthN comes before AuthZ. Example: login=AuthN, accessing admin
page=AuthZ.

Q7. What is JWT? Structure?


Ans: JSON Web Token — self-contained token for stateless auth. Structure: [Link] (Base64 encoded,
dot-separated). Header: algorithm (HS256). Payload: claims (userId, email, roles, exp). Signature: HMAC of
header+payload with secret key. Server validates signature, no DB lookup needed.
// JWT example (decoded)
// Header: {"alg":"HS256","typ":"JWT"}
// Payload: {"sub":"123","email":"alice@[Link]","roles":["USER"],"exp":1234567890}
// Signature: HMAC-SHA256(base64(header)+"."+base64(payload), secret)
// Full token: eyJhbGc...eyJzdWI...SflKxw...
■ JWT asked in all companies with Spring Security

Q8. Cookies vs Sessions vs JWT — which to use?


Ans: Session: server stores state (session ID in cookie) — stateful, doesn't scale horizontally without sticky
sessions/Redis. JWT: stateless, server stores nothing, scales horizontally, but cannot invalidate before expiry (use short
expiry + refresh token). Use JWT for REST APIs and microservices. Sessions for traditional web apps.

Q9. What are CSRF and XSS attacks?


Ans: CSRF (Cross-Site Request Forgery): tricks user's browser into making unwanted request to site where they're
logged in. Prevention: CSRF tokens, SameSite cookie attribute. XSS (Cross-Site Scripting): inject malicious JS into web
page. Prevention: escape/sanitize user input, Content-Security-Policy header, use textContent not innerHTML.
■ PHASE 13 — Spring Boot & REST API

13.1 Spring Core


Q1. IoC and DI — types?
Ans: IoC: Spring container controls object creation. DI types: Constructor injection (RECOMMENDED — immutable,
testable), Setter (optional deps), Field @Autowired (avoid — hard to test).

Q2. @Component vs @Service vs @Repository vs @RestController?


Ans: All @Component specializations. @Repository: DAO + exception translation. @Service: business logic.
@Controller: MVC views. @RestController = @Controller + @ResponseBody (returns JSON directly).

Q3. Bean scopes?


Ans: singleton (default): one per container. prototype: new each time. request/session/application: web-scoped.

13.2 Spring Boot


Q4. Spring Boot auto-configuration?
Ans: @EnableAutoConfiguration scans [Link]. Each AutoConfig class uses @Conditional:
@ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty. Only configures what's missing and
needed.

Q5. [CODING] Complete REST Controller with validation.


@RestController @RequestMapping("/api/v1/users")
public class UserController{
@Autowired UserService svc;
@GetMapping public ResponseEntity<List<User>> all(){return [Link]([Link]());}
@GetMapping("/{id}") public ResponseEntity<User> byId(@PathVariable Long id){
return [Link](id).map(ResponseEntity::ok).orElse([Link]().build());}
@PostMapping public ResponseEntity<User> create(@Valid @RequestBody UserDto dto){
return [Link](201).body([Link](dto));}
@PutMapping("/{id}") public ResponseEntity<User> update(@PathVariable Long id,@Valid @RequestBody User
Dto dto){
return [Link]([Link](id,dto));}
@DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable Long id){
[Link](id);return [Link]().build();}
}

Q6. Global exception handling?


@RestControllerAdvice
public class GlobalExHandler{
@ExceptionHandler([Link])
ResponseEntity<String> notFound(ResourceNotFoundException e){
return [Link](404).body([Link]());}
@ExceptionHandler([Link])
ResponseEntity<Map<String,String>> validation(MethodArgumentNotValidException e){
Map<String,String> err=new HashMap<>();
[Link]().getFieldErrors().forEach(fe->[Link]([Link](),[Link]()));
return [Link]().body(err);}
}

13.3 Spring Data JPA


Q7. N+1 problem and fix?
Ans: Loading N parents → N extra queries for associations. Fix: JOIN FETCH in JPQL, @EntityGraph, or @BatchSize.
@Query("SELECT o FROM Order o JOIN FETCH [Link] WHERE [Link]=:id")
List<Order> findWithItems(@Param("id")Long id);
Q8. [CODING] Repository with all query types.
public interface UserRepo extends JpaRepository<User,Long>{
List<User> findByEmail(String email);
List<User> findByNameContainingIgnoreCase(String name);
List<User> findTop5ByOrderBySalaryDesc();
@Query("SELECT u FROM User u WHERE [Link]>:min")
List<User> highEarners(@Param("min")double min);
@Modifying @Transactional
@Query("UPDATE User u SET [Link]=false WHERE [Link]<:d")
int deactivate(@Param("d")LocalDate d);
}

13.4 Testing
Q9. [CODING] Unit test with Mockito.
@ExtendWith([Link])
class UserServiceTest{
@Mock UserRepository repo;
@InjectMocks UserService svc;
@Test void findById_success(){
when([Link](1L)).thenReturn([Link](new User(1L,"Alice")));
assertEquals("Alice",[Link](1L).getName());
verify(repo).findById(1L);
}
@Test void findById_notFound(){
when([Link](99L)).thenReturn([Link]());
assertThrows([Link],()->[Link](99L));
}
}
■ PHASE 14 — Spring Security & JWT

14.1 Spring Security Basics


Q1. What is Spring Security?
Ans: Powerful authentication and authorization framework for Spring apps. Features: username/password auth, JWT,
OAuth2, LDAP, role-based access, CSRF protection, session management, method-level security (@PreAuthorize).
■ Spring Security + JWT asked in all companies above 6 LPA

Q2. Spring Security filter chain?


Ans: Requests pass through chain of filters. Key filters: UsernamePasswordAuthenticationFilter (login),
JwtAuthenticationFilter (validate JWT), ExceptionTranslationFilter (handle auth errors), FilterSecurityInterceptor
(authorization). Custom JWT filter plugged before UsernamePasswordAuthenticationFilter.

Q3. [CODING] SecurityConfig with JWT.


@Configuration @EnableWebSecurity
public class SecurityConfig{
@Autowired JwtAuthFilter jwtFilter;
@Bean SecurityFilterChain chain(HttpSecurity http)throws Exception{
return [Link](c->[Link]())
.sessionManagement(s->[Link](STATELESS))
.authorizeHttpRequests(a->a
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.addFilterBefore(jwtFilter,[Link])
.build();
}
@Bean PasswordEncoder encoder(){return new BCryptPasswordEncoder();}
}

14.2 JWT Implementation


Q4. [CODING] JWT generation and validation.
@Component
public class JwtUtil{
@Value("${[Link]}") private String secret;
private final long EXPIRY=1000*60*60*24; // 24h
public String generate(UserDetails user){
return [Link]()
.setSubject([Link]())
.setIssuedAt(new Date())
.setExpiration(new Date([Link]()+EXPIRY))
.signWith([Link]([Link]()),SignatureAlgorithm.HS256)
.compact();
}
public String extractUsername(String token){
return [Link]().setSigningKey([Link]())
.build().parseClaimsJws(token).getBody().getSubject();
}
public boolean isValid(String token,UserDetails user){
return extractUsername(token).equals([Link]())&&!isExpired(token);
}
}
Q5. What is BCrypt? Why use it?
Ans: Adaptive password hashing algorithm. Salted: random salt added before hash (different hash for same password).
Adaptive: cost factor makes it intentionally slow (prevents brute force). Never store plain text or MD5/SHA1 passwords.
BCryptPasswordEncoder in Spring Security.

Q6. What is OAuth2? Key roles?


Ans: Authorization framework for delegated access. Key roles: Resource Owner (user), Client (your app), Authorization
Server (Google/GitHub — issues tokens), Resource Server (API with protected resources). Flows: Authorization Code
(web apps — most secure), Implicit (deprecated), Client Credentials (machine-to-machine), Password (legacy).

Q7. Access token vs Refresh token?


Ans: Access token: short-lived (15min-1hr), used to access APIs. Refresh token: long-lived (days/weeks), stored
securely, used to get new access token when expired. Strategy: store refresh token in httpOnly cookie (XSS-safe), access
token in memory.
■ PHASE 15 — Modern Java 17 / 21

15.1 Java 14-17 Features


Q1. What are Records in Java 16+?
Ans: Concise immutable data classes. Auto-generates: constructor, getters (field name as method), equals(),
hashCode(), toString(). Cannot extend classes. Can implement interfaces. Can have custom methods.
// Before records
class Point{private final int x,y; Point(int x,int y){this.x=x;this.y=y;} int x(){return x;} /* ... */}
// With records
record Point(int x,int y){} // that's it!
record User(String name,String email){
// compact constructor for validation
User{[Link](name,"name required");}
String displayName(){return name+" <"+email+">";}
}
Point p=new Point(3,4); p.x(); p.y(); // getters
■ Records asked in modern Java interviews — Atlassian, Thoughtworks, startups

Q2. What are Sealed Classes in Java 17?


Ans: Restrict which classes can extend/implement them. Use permits keyword. Subclasses must be final, sealed, or
non-sealed. Enables exhaustive pattern matching. Great for domain modeling (Result type, ADTs).
sealed interface Shape permits Circle,Rectangle,Triangle{}
record Circle(double radius) implements Shape{}
record Rectangle(double w,double h) implements Shape{}
// Exhaustive switch — compiler ensures all cases covered
double area=switch(shape){
case Circle c -> [Link]*[Link]()*[Link]();
case Rectangle r -> r.w()*r.h();
case Triangle t -> 0.5*[Link]()*[Link]();
};

Q3. What is Pattern Matching for instanceof (Java 16)?


Ans: Combines instanceof check + cast into one expression. Eliminates explicit cast. Works in switch expressions too
(Java 21 finalized).
// Before Java 16
if(obj instanceof String){String s=(String)obj; [Link]([Link]());}
// Java 16+ pattern matching
if(obj instanceof String s) [Link]([Link]()); // s auto-cast
// Java 21 switch pattern matching
String result=switch(obj){
case Integer i -> "int: "+i;
case String s -> "str: "+[Link]();
case null -> "null";
default -> "other";
};

Q4. What are Text Blocks (Java 15)?


Ans: Multi-line strings with triple quotes. No need for escape characters. Preserves formatting. Incidental whitespace
stripped automatically.
String json = """
{ "name": "Alice", "age": 25 }
""";
String sql = """
SELECT [Link], d.dept_name FROM users u
JOIN departments d ON u.dept_id=[Link] WHERE [Link]=true
""";

15.2 Java 21 Features


Q5. What are Virtual Threads (Java 21)?
Ans: Lightweight threads managed by JVM (not OS). Millions can be created (vs thousands of platform threads). Blocking
virtual thread unmounts from carrier thread — carrier handles other work (no wasted threads). Huge benefit for I/O-bound
apps (web servers, DB calls). Use [Link]().
// Java 21 virtual threads
try(var executor=[Link]()){
[Link](0,100_000).forEach(i->
[Link](()->{ [Link](1000); [Link](i); }));
} // 100,000 threads — works fine with virtual threads!
// Spring Boot 3.2+ enable virtual threads:
// [Link]=true

Q6. What are Sequenced Collections (Java 21)?


Ans: New interfaces: SequencedCollection (getFirst/getLast/addFirst/addLast/reversed), SequencedSet, SequencedMap.
Implemented by ArrayList, LinkedList, LinkedHashSet, LinkedHashMap, TreeMap etc. Gives consistent API for ordered
collections.
■■ PHASE 16 — DSA + Design Patterns + SOLID

16.1 Design Patterns


Q1. [CODING] Factory pattern.
interface Notification{void send(String msg);}
class NotifFactory{
static Notification create(String type){
return switch(type){
case "email"->new EmailNotif();
case "sms"->new SMSNotif();
default->throw new IllegalArgumentException(type);
};
}
}

Q2. [CODING] Observer pattern.


interface Observer{void update(String event);}
class EventBus{
private List<Observer> obs=new ArrayList<>();
void subscribe(Observer o){[Link](o);}
void publish(String e){[Link](o->[Link](e));}
}

Q3. [CODING] Strategy pattern.


interface SortStrategy{void sort(int[] a);}
class Sorter{private SortStrategy s; Sorter(SortStrategy s){this.s=s;} void sort(int[] a){[Link](a);}}

Q4. SOLID principles?


Ans: S: Single Responsibility — one reason to change. O: Open/Closed — extend not modify. L: Liskov — subclass
substitutable. I: Interface Segregation — no unused methods. D: Dependency Inversion — depend on abstractions.

16.2 DSA Coding


Q5. [CODING] Two Sum O(n).
int[] twoSum(int[] n,int t){Map<Integer,Integer> m=new HashMap<>();for(int i=0;i<[Link];i++){int c=t-n[i
];if([Link](c))return new int[]{[Link](c),i};[Link](n[i],i);}return new int[]{};}

Q6. [CODING] Reverse Linked List.


ListNode reverse(ListNode h){ListNode p=null,c=h;while(c!=null){ListNode n=[Link];[Link]=p;p=c;c=n;}return
p;}

Q7. [CODING] Valid Parentheses.


boolean isValid(String s){Deque<Character> st=new ArrayDeque<>();for(char c:[Link]()){if(c=='('||c=
='['||c=='{')[Link](c);else{if([Link]())return false;char t=[Link]();if(c==')'&&t!='('||c==']'&&t!='[
'||c=='}'&&t!='{')return false;}}return [Link]();}

Q8. [CODING] Kadane's Algorithm.


int maxSubArray(int[] n){int max=n[0],cur=n[0];for(int i=1;i<[Link];i++){cur=[Link](n[i],cur+n[i]);max
=[Link](max,cur);}return max;}

Q9. [CODING] Binary Search.


int binarySearch(int[] a,int t){int lo=0,hi=[Link]-1;while(lo<=hi){int mid=lo+(hi-lo)/2;if(a[mid]==t)ret
urn mid;else if(a[mid]<t)lo=mid+1;else hi=mid-1;}return -1;}

Q10. [CODING] Level order traversal BFS.


List<List<Integer>> levelOrder(TreeNode root){
List<List<Integer>> res=new ArrayList<>();
if(root==null)return res;
Queue<TreeNode> q=new LinkedList<>();[Link](root);
while(![Link]()){int sz=[Link]();List<Integer> lv=new ArrayList<>();
for(int i=0;i<sz;i++){TreeNode n=[Link]();[Link]([Link]);
if([Link]!=null)[Link]([Link]);if([Link]!=null)[Link]([Link]);}[Link](lv);}return res;}

Q11. [CODING] Detect cycle in linked list.


boolean hasCycle(ListNode h){ListNode s=h,f=h;while(f!=null&&[Link]!=null){s=[Link];f=[Link];if(s==f)
return true;}return false;}

Q12. [CODING] Find missing number 1 to N.


int missingNumber(int[] a){int n=[Link],sum=n*(n+1)/2;for(int x:a)sum-=x;return sum;}
■ PHASE 17 — DevOps & Deployment

17.1 Git
Q1. Key Git commands?
Ans: git init, clone, add, commit -m, push, pull, fetch, merge, rebase, branch, checkout, stash, log, diff, status, reset
(--soft/--hard), revert, cherry-pick, tag.

Q2. git merge vs git rebase?


Ans: merge: creates merge commit, preserves full history, non-destructive. rebase: replays commits on new base, linear
history, rewrites commits. Use merge for shared branches; rebase for local cleanup before PR. NEVER rebase shared
branches.

Q3. What is a Pull Request (PR)?


Ans: Request to merge your branch into main/develop. Contains: code changes, description, linked issue. Goes through:
code review → CI checks → approval → merge. Best practice: small focused PRs, descriptive title, reference issue
number.

17.2 Docker
Q4. What is Docker? Key concepts?
Ans: Containerization platform. Container: isolated environment with app + dependencies (lightweight, portable). Image:
read-only template to create containers. Dockerfile: instructions to build image. Registry: Docker Hub stores images. vs
VM: containers share OS kernel (lighter, faster).
■ Docker asked in all companies above 8 LPA

Q5. [CODING] Dockerfile for Spring Boot app.


# Multi-stage build
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /app
COPY [Link] .
COPY src ./src
RUN ./mvnw package -DskipTests

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /app/target/*.jar [Link]
EXPOSE 8080
ENTRYPOINT ["java","-jar","[Link]"]

Q6. Docker Compose — what is it?


Ans: Define and run multi-container apps. YAML file specifies services, networks, volumes.
version:'3.8'
services:
app:
build:.
ports:["8080:8080"]
environment:
SPRING_DATASOURCE_URL:jdbc:mysql://db:3306/mydb
depends_on:[db]
db:
image:mysql:8
environment:{MYSQL_DATABASE:mydb,MYSQL_ROOT_PASSWORD:secret}
volumes:[mysql_data:/var/lib/mysql]
volumes: {mysql_data:{}}

Q7. Key Docker commands?


Ans: docker build -t name:tag . | docker run -p 8080:8080 image | docker ps (running) | docker images | docker stop/rm |
docker logs | docker exec -it container bash | docker pull/push | docker-compose up -d | docker-compose down

17.3 CI/CD
Q8. What is CI/CD?
Ans: CI (Continuous Integration): automatically build + test on every commit. CD (Continuous Delivery): auto deploy to
staging after CI. CD (Continuous Deployment): auto deploy to production. Tools: GitHub Actions, Jenkins, GitLab CI,
CircleCI.

Q9. [CODING] GitHub Actions workflow for Spring Boot.


name:CI
on:[push,pull_request]
jobs:
build:
runs-on:ubuntu-latest
steps:
- uses:actions/checkout@v4
- uses:actions/setup-java@v4
with:{java-version:'21',distribution:'temurin'}
- run:mvn clean test
- run:mvn package -DskipTests
- uses:docker/build-push-action@v5
with:{push:true,tags:myapp:latest}
■■ PHASE 18 — System Design Basics

18.1 Architecture Patterns


Q1. Monolith vs Microservices?
Ans: Monolith: single deployable unit, simple to develop/debug, scales as whole, harder to maintain as it grows.
Microservices: independent services per domain, separate deploy/scale, tech diversity, complex (distributed system —
network failures, eventual consistency, service discovery). Start monolith, extract services when needed.
■ Asked in senior roles — Amazon, Flipkart, Paytm 8+ LPA

Q2. What is an API Gateway?


Ans: Single entry point for all client requests. Responsibilities: routing, authentication, rate limiting, load balancing, SSL
termination, logging, circuit breaking. Examples: Spring Cloud Gateway, Kong, AWS API Gateway, Nginx.

Q3. What is a Circuit Breaker pattern?


Ans: Prevents cascade failures in distributed systems. States: CLOSED (normal, requests pass), OPEN (failure threshold
exceeded, requests fail fast — no downstream calls), HALF-OPEN (test recovery — few requests allowed). Hystrix
(legacy) or Resilience4j (modern).

18.2 Caching & Performance


Q4. What is caching? Cache strategies?
Ans: Store frequently accessed data in fast storage (memory) to reduce DB load and latency. Strategies: Cache-aside
(app checks cache first, on miss: load from DB + populate cache). Write-through (write to cache + DB simultaneously).
Write-back (write cache, async sync to DB — risk of data loss). TTL: time-to-live for cache expiry.

Q5. What is Redis? Use cases?


Ans: In-memory data store. Supports: strings, hashes, lists, sets, sorted sets. Use cases: caching (session, API
responses), rate limiting, pub/sub messaging, leaderboards (sorted sets), distributed locks. Persistence: RDB snapshots
or AOF (append-only file).
// Spring Boot Redis cache
@Cacheable(value="users",key="#id")
public User findById(Long id){return [Link](id).orElseThrow();}
@CacheEvict(value="users",key="#id")
public void deleteUser(Long id){[Link](id);}
// [Link]
// [Link]=localhost
// [Link]=6379

18.3 Messaging & Scaling


Q6. What is Kafka? Key concepts?
Ans: Distributed streaming platform. Key: Topic (category/feed), Partition (parallelism unit), Producer (publishes),
Consumer (subscribes), Consumer Group (load balancing), Broker (Kafka server), Offset (position in partition). Use:
event-driven architecture, async decoupling, high-throughput logging.

Q7. Horizontal vs Vertical scaling?


Ans: Vertical (scale up): add more CPU/RAM to existing server. Simple but has hardware limits, single point of failure.
Horizontal (scale out): add more servers. Requires load balancer, stateless apps, more complex but unlimited scale. Use
horizontal for production microservices.

Q8. What is load balancing? Algorithms?


Ans: Distributes requests across multiple servers. Algorithms: Round Robin (sequential), Least Connections (to server
with fewest), IP Hash (same client → same server for sticky sessions), Weighted (based on server capacity). Tools:
Nginx, AWS ALB, HAProxy.

Q9. What is CAP theorem?


Ans: Distributed system can guarantee only 2 of 3: Consistency (all nodes see same data simultaneously), Availability
(every request gets a response), Partition Tolerance (system works despite network partitions). Since network partitions
are unavoidable: choose CP (MySQL, HBase) or AP (Cassandra, DynamoDB).

Q10. What is database sharding?


Ans: Horizontal partitioning — split data across multiple DBs (shards) by shard key (userId, region). Each shard holds
subset of data. Enables horizontal DB scaling. Challenges: cross-shard queries, rebalancing, distributed transactions.
■ You Are Now FULLY Prepared!
Java Full Stack Developer — 2026 Edition
800+ Questions | 18 Phases | Backend + Frontend + Security + DevOps + System Design

■ COMPLETE PREPARATION CHECKLIST — NOTHING LEFT OUT

■ PHASE 1-6: Core Java, OOP, Collections, Java 8, Threads, I/O

■ PHASE 7-8: MySQL (Joins, Window Fns, Indexes) + JDBC (PreparedStatement, Transactions)

■ PHASE 9-10: HTML5 + CSS (Flexbox, Grid, RWD) + JavaScript (Closures, Promises, ES6+)

■ PHASE 11: React (Hooks, Context, Redux, Router, Axios)

■ PHASE 12: HTTP, REST, CORS, JWT, OAuth2, CSRF, XSS

■ PHASE 13-14: Spring Boot REST + Spring Security + JWT Implementation

■ PHASE 15: Modern Java 17/21 (Records, Sealed, Virtual Threads)

■ PHASE 16: DSA (Two Sum, BFS, Kadane's) + Design Patterns + SOLID

■ PHASE 17: Git, Docker, Docker Compose, GitHub Actions CI/CD

■ PHASE 18: System Design (Microservices, Redis, Kafka, CAP, Sharding)

■ FINAL TIPS

■ Build 2 full-stack projects: Spring Boot REST + React frontend + MySQL

■ Deploy on AWS EC2 or [Link] — practical experience is gold

■ Practise SQL daily on HackerRank, LeetCode DB problems

■ For coding rounds: LeetCode Easy + Medium (Two Sum, Valid Parens, BFS/DFS)

■ Think out loud — interviewers evaluate your thought process

■ Know time + space complexity for every solution

You might also like