Skip to main content

Roadmap

Java and Python roadmap, stage by stage

Pick a programme to see its stages in order. Open "See all topics" under a stage for every module and lesson.

Programme

From your first program to job-ready

Java roadmap

One clear path from your first line of Java to exam-ready skills, coding interviews, backend applications and your first tech job.

Java developer roadmap for beginners: the stages, with DSA and interview prep

  1. Stage 1: Learn Java

    Build your programming foundation

    • Java Basics
    • Developer Setup
    • Git & GitHub
    • Git in Practice
    • Java OOP
    • Java Collections & Generics
    See this stage
    See all topics in Learn Java
    1. Java Basics

      Variables, operators, input and output, conditions, loops, methods, arrays, strings and exceptions, ending with mini projects.

      • Getting Started

      • Variables & Data Types

      • Operators

      • Input & Output

        • Printing with println and print: Use println and print, Print special characters with escape sequences, Join text and values with +, Use brackets to add numbers inside a message
        • Formatted output with printf: Print values with printf, Use %d, %.2f, %s and %n, Round decimals and print a % sign, Build a formatted String with String.format
        • Reading input with Scanner: Import and create a Scanner, Show a prompt before reading, Read text with nextLine(), Read a whole number with nextInt()
        • Reading numbers, words and characters: Pick the right Scanner method for each type, Read decimals with nextDouble(), Read several values from one line, Read one character
        • next() vs nextLine() and the Enter key: Choose between next() and nextLine(), Explain the leftover Enter after nextInt(), Fix it with an extra nextLine(), Read text before numbers
        • Common input errors: Explain InputMismatchException, Fix a missing Scanner import, Write clear prompts, Close the Scanner at the right place
        • Mini programs and practice: Plan a small console program, Combine Scanner input with printf output, Pick the right Scanner method, Avoid the common input and output mistakes
      • Conditional Statements

      • Loops

        • Why loops?: Explain what a loop is, Name the three parts of a loop, Explain what an iteration is, Name the three loops in Java
        • The for loop: Write a for loop with start, condition and update, Explain the order in which a for loop runs, Count up, count down and count in steps, Print a multiplication table with a loop
        • Tracing a loop: totals and counts: Trace a loop with a trace table, Keep a running total in a loop, Count items with a counter, Find a product such as a factorial
        • while and do-while loops: Write a while loop with a start, condition and update, Choose between for and while, Write a do-while loop, Explain why do-while runs at least once
        • break and continue: Stop a loop early with break, Skip a round with continue, Trace a loop that uses break and continue, Avoid the continue trap in a while loop
        • Nested loops and star patterns: Explain how a nested loop runs, Print rows and columns with print and println, Print square and triangle star patterns, Print number patterns and a multiplication grid
        • Common mistakes and practice: Choose between for, while and do-while, Fix off-by-one mistakes, Find and fix infinite loops, Spot a semicolon after for and a changed loop variable
        • Must-do problems: Loops: 10 easy problems, 12 medium problems, 8 hard problems
      • Methods

        • Why use methods?: Explain what a method is, Explain why methods avoid repeated code, Recognise methods you already use, like println
        • Define and call a method: Write a method with static void, Call a method from main, Trace the order in which methods run, Name methods in camelCase
        • Parameters and arguments: Write a method with one or more parameters, Pass arguments in the right order, Explain the difference between a parameter and an argument
        • Return a value from a method: Write a method with a return type and return, Store and use a returned value, Choose between void and a return type, Fix missing return statement
        • Local variables and scope: Explain what a local variable is, Find the scope of a variable, Explain why each call starts with fresh variables, Describe the call stack in simple words
        • Pass-by-value: a method gets a copy: Explain pass-by-value for primitive types, Predict that a parameter change does not change the caller, Return a changed value and store it
        • Method overloading: Write overloaded methods, Predict which overloaded method Java calls, Explain why only the return type cannot differ
        • Recursion: a method that calls itself: Explain base case and recursive call, Trace a small recursive method, Write countdown, factorial and sum with recursion
        • Common mistakes and practice: Find and fix common method mistakes, Choose void or a return type, Write small programs that combine several methods
        • Must-do problems: Methods: 8 easy problems, 8 medium problems, 4 hard problems
      • Arrays

        • What is an array?: Explain what an array is, Explain elements and indexes, starting from 0, Read one element with its index, Explain why an array has one type and a fixed size
        • Creating an array: Declare an array variable, Create an array with values in { }, Create an array with a size using new, Know the default values of a new array
        • Reading and changing array elements: Read and change one element with its index, Get the size of an array with length, Get the last element with length - 1, Explain ArrayIndexOutOfBoundsException
        • Looping through an array: Visit every element with a for loop, Use i < length to stay inside the array, Loop through an array backwards, Fill an array with a loop and with Scanner input
        • The for-each loop: Write a for-each loop over an array, Choose between for-each and an index loop, Explain why for-each cannot change the array
        • Sum, average, largest and search: Find the total and average of an array, Find the largest and smallest element, Count the elements that match a condition, Search an array for a value
        • Arrays and methods: Pass an array to a method, Return an array from a method, Explain that an array variable holds a reference, Make a real copy of an array
        • 2D arrays: rows and columns: Create a 2D array with a size or with values, Read and change an element with a row and a column index, Get the number of rows and columns, Visit every element with nested loops
        • The Arrays class: print, sort and compare: Print an array with Arrays.toString, Sort an array with Arrays.sort, Compare two arrays with Arrays.equals, Fill and copy an array with Arrays.fill and Arrays.copyOf
        • Common mistakes and practice: Find and fix index out of bounds and off-by-one mistakes, Print arrays correctly, Avoid wrong starting values for max and min, Solve mixed array problems
        • Must-do problems: Arrays: 10 easy problems, 12 medium problems, 8 hard problems
      • Strings

        • String recap: characters and index positions: Recall String literals, + and length(), Find the index of any character in a String, Read one character with charAt(), Check for an empty String with isEmpty()
        • Search in a String: indexOf, contains, startsWith: Find the position of a character or word with indexOf(), Understand that -1 means "not found", Use lastIndexOf() to search from the end, Check text with contains(), startsWith() and endsWith()
        • Cut out part of a String with substring(): Use substring(start, end) and remember the end is not included, Use substring(start) to take the rest of a String, Combine indexOf() and substring() to split an email or a name, Avoid StringIndexOutOfBoundsException with substring()
        • Change case, trim and replace (Strings never change): Explain what immutable means for a String, Store the result of a String method, Change case with toUpperCase() and toLowerCase(), Remove extra spaces with trim() and strip(), and check isBlank(), Replace text with replace() and repeat text with repeat()
        • Compare Strings: equals() and compareTo(): Compare text with equals() and equalsIgnoreCase(), Explain why == can give false for the same text, Know what the String pool is, Put two Strings in dictionary order with compareTo()
        • Loop through the characters of a String: Loop over a String with charAt(i), Compare a char with == and single quotes, Use Character.isDigit(), isLetter(), isUpperCase() and toLowerCase(), Use toCharArray() with a for-each loop
        • Split, join and turn text into numbers: Split a String into an array with split(), Split on one or more spaces with split("\\s+"), Join parts with String.join(), Turn text into numbers with Integer.parseInt() and Double.parseDouble()
        • Build and change text with StringBuilder: Create a StringBuilder and add text with append(), Change text with insert(), reverse(), deleteCharAt() and setCharAt(), Turn a StringBuilder into a String with toString(), Explain why StringBuilder is faster than + in a loop
        • Common mistakes and practice: Spot and fix == on Strings and unstored String results, Avoid index errors with charAt(), substring() and indexOf(), Avoid the char + char surprise, Solve small String programs: palindrome, word count, initials, reverse words
        • Must-do problems: Strings: 10 easy problems, 12 medium problems, 8 hard problems
        • String methods: quick reference: Inspect, cut and search, Compare text, Change case, spaces and text, Split, join and convert
      • Exception Basics

        • What is an exception?: Explain what an exception is, Tell a compile error from an exception, Read a stack trace: name, message and line number
        • Common exceptions you will see: Name the common runtime exceptions, Say what causes each one, Prevent them with simple checks
        • Handle an exception with try and catch: Write a try-catch block, Know which lines run and which are skipped, Print the exception message with getMessage()
        • Multiple catch blocks: Write a try with several catch blocks, Order catch blocks from specific to general, Catch two exception types in one block with |
        • The finally block: Write try-catch-finally, Know when finally runs, Close a Scanner in finally
        • throw and throws: Throw an exception with throw, Tell checked and unchecked exceptions apart, Declare a checked exception with throws
        • Keep asking until the input is valid: Loop until the user types a valid number, Clear bad input with nextLine(), Read a line and convert it with parseInt, Combine a number check and a range check
        • Common mistakes and practice: Avoid empty catch blocks and silent errors, Catch specific exceptions instead of Exception everywhere, Choose between an if check and try-catch, Solve mixed exception problems
        • Must-do problems: Exception Basics: 6 easy problems, 6 medium problems, 3 hard problems
      • Packages, Imports & Access Control

        • Why do we need packages?: Explain what a Java package is, Explain why packages are used, Read and write a full class name, Name the packages of String, Math, Scanner and Arrays
        • Create your own package: Write a package statement, Save a class in the folder that matches its package, Compile with javac -d and run with the full class name, Create a package in an IDE
        • Use classes from other packages with import: Use a class from another package by full name or import, Choose between a single-class import and a wildcard import, Know which classes need no import, Fix missing imports and name clashes
        • Access modifiers: public, private and default: Name Java's four access levels and who can use each, Hide a field with private and expose public methods, Use default (package) access, Read access compile errors
        • Build an app with two packages: Name packages the standard way, Split a small app into packages by topic, Choose public and private for each member, Compile and run an app with several packages
        • Common mistakes and practice: Fix package line and run command mistakes, Fix missing, wrong and clashing imports, Fix private and default access errors, Solve mixed package and access problems
      • Java Basics Mini Projects

        • Build a simple calculator: Build a menu loop with Scanner input, Use a switch expression inside a method, Format results with printf, Push a Java project to GitHub
        • Build a number guessing game: Pick random numbers with Random, Control a loop with two conditions, Use continue and do-while, Push a Java project to GitHub
        • Build a student marks report: Store related data in parallel arrays, Write methods that take arrays, Validate input with a loop, Print aligned tables with printf
        • Build a text analyzer: Split text into words, Loop over the characters of a String, Build and reverse text with StringBuilder, Check for palindromes
        • Build an ATM simulator: Pass values into methods and return the new value, Validate input with try/catch, Combine loops, switch and methods, Push a Java project to GitHub
    2. Developer Setup

      Work like a developer from day one: the command line, folders and files, PATH and environment variables.

    3. Git & GitHub

      Git version control and GitHub, shared by every MentorNxt course: commits, branches, merge conflicts, pull requests with code review, forks and issues.

      • Git Basics

      • Branches & Merging

        • Branches: create one and switch to it: A branch is a movable label, What HEAD is, git branch, switch and switch -c, Switching with uncommitted changes
        • Merging branches: Fast-forward vs merge commit, Three-way merges and the merge base, Deleting merged branches: -d vs -D, Merging main into a feature branch
        • Merge conflicts: Why conflicts happen, Reading conflict markers, Resolving in the editor and the IDE merge tool, Finishing or aborting a merge
        • Common mistakes and practice: The feature branch loop, A commit on the wrong branch, Detached HEAD, A merge blocked by local changes
      • GitHub & Teamwork

        • Put your project on GitHub: Git vs GitHub, public vs private, git remote add and push -u, Signing in with a token or SSH, Cloning, and first-push errors
        • Clone, push, pull and fetch: origin/main: Git's saved copy of the remote, Ahead, behind and diverged, Fetch vs pull, A rejected push and why not to force it
        • Write a README in Markdown: Markdown syntax, What a good README has, Your GitHub profile README, Choosing a licence
        • Pull requests and code review: The feature branch workflow, A clear pull request description, Reviewing and replying with new commits, Updating with main, merging and cleaning up
        • Forks, issues and open source: Fork vs clone, The upstream remote and syncing a fork, Issues and good bug reports, Closing issues from pull requests
        • Common mistakes and practice: Unrelated histories after 'Add a README', 'Everything up-to-date' with uncommitted work, Conflicts during pull, What to do about a leaked secret
    4. Git in Practice

      Three hands-on projects that turn your Basics programs into a GitHub portfolio: a portfolio repository, a feature-branch pull request and a merge-conflict drill.

    5. Java OOP

      Classes, constructors, encapsulation, inheritance, polymorphism, interfaces, enums, equality, copying and immutability, ending with mini projects.

      • Classes & Objects

      • Constructors

        • What is a constructor?: See why objects start empty, Follow what happens at new, step by step, Compare a constructor with a method, Spot the void Student() trap
        • The default constructor: Know when Java adds a default constructor, Use field initializers like int seats = 40, Fix the error after writing a constructor, Write your own no-argument constructor
        • Constructors with parameters: Match arguments in number, type and order, Read required and found in javac errors, Catch swapped same-type arguments, Refuse bad values with IllegalArgumentException
        • The this keyword: Fix the shadowing bug with this.field, Use this as the current object, Pass this and return this for chaining, Know where this cannot be used
        • Constructor overloading: Give a class several constructors, Predict which constructor javac picks, Fix already defined and no suitable constructor errors, Spot a check missing from one overload
        • Call one constructor from another with this(): Let one full constructor do the work, Put this(...) first, Trace initializers and constructor bodies in order, Fix recursive constructor invocation
        • Common mistakes and practice: Fix mistakes in writing a constructor, Fix mistakes in calling a constructor, Find constructor bugs that compile, Follow a five-step plan for any class
        • Must-do problems: Constructors: 5 easy problems, 4 medium problems, 3 hard problems
      • Encapsulation

        • Why encapsulation?: Spot wrong values in open fields, Hide fields behind checking methods, Read the has private access error, Let the class own its rules
        • private fields and public methods: Compare the four access levels, Spot the default-access trap, Use private access between objects of one class, Write private helpers and constructors
        • Getters and setters: Name getters and setters, including isX, Use this in setters, Fix the x = x setter bug, Decide when not to add a setter
        • Keep objects valid with checks: Check a value before saving it, Throw IllegalArgumentException instead of printing, Have the constructor call the setter, Catch validation errors in main
        • Read-only fields and computed values: Make fields read-only with no setter, Replace stored totals with computed getters, See the getter and constructor array leaks, Fix leaks with Arrays.copyOf
        • Design methods, not just setters: Replace setBalance with deposit and withdraw, Build a UPI wallet with private helpers, Book seats without overbooking, Design a class from a requirement
        • Common mistakes and practice: Read compile errors as protection, Find encapsulation bugs that compile, Hunt and fix bugs in one class, Apply a checklist to every class
        • Must-do problems: Encapsulation: 5 easy problems, 4 medium problems, 3 hard problems
      • Static & Final

        • Instance members and static members: Compare per-object and shared copies, Picture class and object memory, Reach members with ClassName.member, Choose instance or static
        • Static variables: Count objects with count++, Generate IDs from a static counter, Keep shared settings private with static getters, Avoid changing a static field through an object
        • Static methods and why main is static: Write utility methods called as ClassName.method(), Read the real static-context errors, Pass objects into static methods, Explain why main is static
        • Static blocks: Say when a static block runs, Fill a fare table in a static block, Explain instance initializer blocks, Trace the full initialisation order
        • final variables and constants: Use final local variables, Set a blank final in every constructor, Write static final constants in UPPER_SNAKE_CASE, See that a final reference does not freeze the object
        • Common mistakes and practice: Fix compile-time static and final mistakes, Find mistakes that compile but print wrong values, Choose the right kind of field and method, Design an ID generator
        • Must-do problems: Static and Final: 4 easy problems, 4 medium problems, 2 hard problems
      • Inheritance

      • Polymorphism

        • What is polymorphism?: Define many forms, Compare compile-time and runtime polymorphism, Replace an if-else chain with child classes, Write one checkout method for every payment
        • Method overriding and its rules: Override an inherited method, Apply the return-type rule, Keep access the same or wider, Know why private, static and final methods are not overridden
        • The @Override annotation: See the silent typo bug, Read the does not override error, Catch wrong parameters and private parent methods, Know where @Override is not allowed
        • Call the parent's version with super.method(): Extend a parent method instead of replacing it, Build on the value super.method() returns, Fix the StackOverflowError from a missing super., Trace multilevel super chains
        • Overloading vs overriding: Compare overloading and overriding side by side, See that a return type alone is not an overload, Override and overload in the same child, Trace programs that mix both
        • Parent reference, child object (upcasting): Upcast automatically, Tell the reference type from the object type, Fix cannot find symbol for child-only methods, Use parent-type arrays, parameters and return types
        • Dynamic method dispatch: Follow how the JVM finds the method, See a parent method call the child's version, Show that fields are not polymorphic, Show that static methods are not dispatched
        • Common mistakes and practice: Review the module, Find silent polymorphism bugs, Read the errors javac catches, Follow a five-step tracing recipe
        • Must-do problems: Polymorphism: Override rules per child class, Shared steps in a parent method, super.method() up a chain, Overloading with overriding
      • Abstraction & Interfaces

      • Enums

        • Why enums?: How int and String constants go wrong, An enum as a fixed set of named values, Each constant is one object, created once, When to use an enum
        • Built-in enum methods: values(), name(), valueOf(), ordinal(): values(), valueOf(), name() and ordinal(), Why you should not save ordinal(), Comparing enums with ==, Arrow switch and complete switch expressions on an enum
        • switch on an enum: Case labels with the simple constant name, Exhaustive switch expressions without default, How default hides new constants, Switching on a null enum
        • Enums with fields, constructors and methods: Constants with constructor arguments, Rules: constants first, private constructor, private final fields, When the enum constructor runs, A static fromCode() lookup over values()
        • Enums with behaviour and interfaces: Constant-specific bodies with an abstract method, Default bodies that some constants override, Enums implementing an interface; no extends, An order status state machine with next()
        • Common mistakes and practice: The enums module in one picture, Compile errors you will meet, Enum mistakes that compile but cause bugs, Choosing between an enum, a constant and a class
        • Must-do problems: Enums: 4 easy problems, 5 medium problems, 3 hard problems, Enums with data, behaviour, switches and interfaces
      • Composition & Relationships

      • Object Class & Equality

        • The Object class: every class's parent: See the hidden extends Object, List the methods every object inherits, Hold any object in an Object reference, Find the real class with getClass()
        • toString(): print objects nicely: Read the default ClassName@hash, Override toString() with @Override, Know when println calls toString(), Reuse the parent text with super.toString()
        • == compares references: See that variables hold references, Tell identity from logical equality, Avoid the String and array == traps, Use == for null checks
        • Write your own equals(): Apply the five-step equals recipe, Compare fields with ==, equals or Objects.equals, Spot the equals(Student other) overload bug, Know the rules equals must follow
        • hashCode() and the equals/hashCode contract: Explain hash codes and buckets, State the equals/hashCode contract, Show what breaks without hashCode, Write hashCode with Objects.hash
        • Common mistakes and practice: Fix == and equals mistakes, Fix hashCode mistakes, Store money as whole paise, Base identity on a stable final id
        • Must-do problems: Object Class and Equality: toString() and equals() by chosen fields, Null-safe equality with Objects.equals, Duplicates and lookups with equals() and hashCode(), Your own hash table and stable ids
      • Copying Objects

        • Assignment is not a copy: b = a copies the reference, not the object, When sharing one object is a bug, What a real copy is: == false, same data, independent changes, Copying arrays with =, Arrays.copyOf and clone()
        • Copy constructors and copy methods: Writing a copy constructor like Student(Student other), Copying array fields with clone(), Static copyOf factories and copy() methods, Chaining copies with this(...) and super(other)
        • Shallow copy vs deep copy: A shallow copy shares inner objects, Deep copy level by level, including arrays of objects, When sharing is fine: Strings, enums and parts shared on purpose, Deciding the copy depth field by field
        • clone() and Cloneable: Object.clone() and the Cloneable marker interface, Overriding clone() with super.clone() and a covariant return type, CloneNotSupportedException and making clone() deep, clone() vs copy constructors: honest pros and cons
        • Common mistakes and practice: Mistakes that share too much, and copies that go wrong, Testing a copy with ==, equals() and a change test, A deep copy that stops one level too early, Choosing the right copying tool for each field
        • Must-do problems: Copying Objects: Array and 2D array copies, Copy constructors that deep copy, Share on purpose or copy, Save points and versions
      • References, Casting & Immutability

      • OOP Mastery & Code Tracing

        • Read an unfamiliar OOP program: Start at main and map classes and links, Keep a trace table of objects and references, Follow calls on the call stack, Spot shared objects and inherited calls
        • Trace object creation and constructors: Order static and instance setup, Trace this() and super() chains, Place field initializers and instance blocks, Spot the overridden method in a constructor
        • Trace inheritance and polymorphism: Separate compile-time and run-time choices, Trace super calls that call back into the child, Resolve overloading versus overriding puzzles, Handle field hiding, static and private methods
        • Spot OOP design problems: Fix public fields and setter-only classes, Replace magic numbers and duplicated code, Replace instanceof chains with overriding, Split a god class
        • Find and fix OOP bugs: Read compiler errors and stack traces, Fix NPE and ClassCastException, Fix shadowing and equals/hashCode bugs, Fix hierarchy compile errors
        • Design classes from requirements: Use the noun-verb method, Decide who owns each method, Choose inheritance, composition or an interface, Avoid a class explosion
        • SOLID principles in plain words: Give each class one job, Add features through interfaces, Keep the parent's promises, Use small interfaces and constructor injection
        • Build a multi-class application: Plan a small app before coding, Build it bottom-up step by step, Combine abstract classes, interfaces and composition, Split the app into packages
      • Java OOP Mini Projects

        • Student Profile & Marks Report: Design a Student class with a this constructor, Store students in an array with a count, Work out total, percentage and grade, Find the topper
        • Bank Account Manager: Protect the balance with private fields and no setters, Validate in the constructor and methods, Generate account numbers with a static counter, Throw and catch InsufficientBalanceException
        • Employee Role Hierarchy: Extend Employee into Manager, Developer and Intern, Chain constructors with super(...), Set protected fields from child classes, Lock rules with final methods and a final class
        • Payment Processing Engine: Override method(), fee() and pay() with @Override, Process a Payment[] in one loop, Reuse parent code with super.pay(), Compare overloading and overriding
        • Multi-Channel Notification Service: Define Notifier, Schedulable and MessageFilter interfaces, Share the send steps in an abstract class, Override a default method, Filter spam with a lambda
        • Build a Library Management System: Model has-a with composition and aggregation, Issue and return books with rule checks, Delegate work from Library to Book, Report broken rules with a custom exception
        • Build a Product & Customer Catalogue: Override equals, hashCode and toString together, Compare by a key field with Objects.equals and Objects.hash, Refuse duplicates and search with equals, Show == versus equals
        • Build an Immutable Order & Cart: Model values with records and compact constructors, Build an immutable Order with defensive copies, Return new objects from with-methods, Use a nested static Builder as the cart
        • Capstone: Employee Management & Payroll: Design an interface and abstract class hierarchy, Pay three employee types through one polymorphic call, Give ids from a static counter, Handle errors with a custom exception
    6. Java Collections & Generics

      Generics, lists, sets, maps, queues and sorting: how each works inside and how to choose the right one, ending with mini projects.

      • Generics

        • Why generics?: An Object-based box with casts, ClassCastException at run time, Moving the error to compile time with Box<T>, The diamond and why to avoid raw types
        • Write a generic class: Declaring Box<T> with a constructor and methods, Two type parameters in Pair<K, V>, Wrapper types instead of primitives, Autoboxing, unboxing null and the Integer == trap
        • Generic methods: Declaring static <T> methods, Type inference, Generic helpers: swap, firstOrNull, indexOf, Static methods and the class's T
        • Bounded types: <T extends …>: Why a plain T has only Object methods, <T extends Number>, max with <T extends Comparable<T>>, Multiple bounds with &
        • Wildcards: ?, ? extends, ? super: Why Box<Integer> is not a Box<Number>, The unbounded wildcard ?, Reading with ? extends, writing with ? super, PECS in plain words
        • Type erasure and generic limits: One class at run time and the hidden cast, What you cannot do: new T(), new T[], instanceof Box<String>, Static fields and overloading clashes, Standard workarounds
        • Common mistakes and practice: The four groups of generics mistakes, A generic Result<T> for an exam portal, A leaderboard with a bound and wildcards, Reading a multi-error compile output
      • The Collections Framework

        • Why collections, not arrays?: The fixed-size array crash, Growing and shifting arrays by hand, The same job with ArrayList, Storing numbers as Integer with autoboxing
        • The collection family tree: The collection family tree, Why Map is separate from Collection, Programming to the interface, The error from calling a class-only method
        • Choosing the right collection: The four-question decision guide, Hash, LinkedHash or Tree classes, Big-O in plain words, Measuring list vs set contains
        • Common mistakes and practice: Fixing raw types and ClassCastException, Looping over a map through its views, HashSet has no order, Combining List, Set, Map and Queue
      • Lists

        • ArrayList: add, get, set, remove: Creating a list through the List interface, add, insert, get and set, The remove(int) vs remove(Object) trap, IndexOutOfBoundsException
        • Looping through a list: Index loop, for-each, Iterator and forEach, ConcurrentModificationException and the skip bug, Removing safely with Iterator.remove and removeIf, Changing items with set and replaceAll
        • Iterator and safe removal: Iterator: hasNext, next, remove, Why removing in a for-each loop fails, ConcurrentModificationException, removeIf
        • Search and sort a list: contains and indexOf use equals, Sorting in natural order, Sorting a copy and reversing, binarySearch and the insertion point
        • Lists of your own objects: A list stores references, equals makes contains and remove work, Finding and updating an object in a list, Defensive copies with List.copyOf
        • How ArrayList works inside: Backing array, size and capacity, Growth and amortized O(1) add, Why inserting at the front is slow, Initial capacity and a big-O table
        • LinkedList and when to use it: Nodes and links, addFirst, addLast, getFirst, removeFirst, Why get(i) walks the chain, When to choose LinkedList, honestly
        • Fixed and unmodifiable lists: List.of and UnsupportedOperationException, Arrays.asList: fixed size and write-through, Unmodifiable views vs List.copyOf snapshots, Null rules and shallow read-only lists
        • Common mistakes and practice: Fixing a buggy attendance program, Silent list bugs, The five list exceptions and their causes, A complete marks register
        • Must-do problems: Lists: Easy list problems, Medium list problems, Hard list problems, ArrayList and LinkedList in practice
      • Sorting & Comparing

        • Natural order with Comparable: Reading compareTo results, Implementing Comparable with Integer.compare and compareTo, Sorting objects that are not Comparable, Keeping compareTo consistent with equals
        • Custom order with Comparator: Four ways to write a comparator, Comparator.comparing and comparingInt, reverseOrder and CASE_INSENSITIVE_ORDER, The reversed() type-inference error and its fix
        • Sorting real data: Sorting by several keys with thenComparing, Stable sorting, Handling null fields with nullsFirst and nullsLast, A leaderboard with shared ranks
        • Common mistakes and practice: Overflow in a - b comparators, The (int) cast on double differences, A compareTo that never returns 0, Sorting unmodifiable or shared lists
      • Sets

        • HashSet: no duplicates: add, contains and remove, and their booleans, No order and no index, Why contains is fast, Set.of rules
        • Sets of your own objects: How a set checks: hashCode, then equals, The equals-without-hashCode bug, Choosing key fields and using records, Changing an element after adding it
        • LinkedHashSet and TreeSet: Insertion order vs sorted order, first, last, floor, ceiling, headSet and tailSet, The comparator that drops elements, TreeSet rules for nulls and non-comparable items
        • Union, intersection and difference: addAll, retainAll, removeAll and containsAll, Copy first, then change, Symmetric difference and friend suggestions, Comparing sets with equals
        • Common mistakes and practice: Choosing the right set, Common set mistakes, Removing while looping, Interview problems with sets
        • Must-do problems: Sets: Duplicates and unique counts, Common items between sets, Ordering checks, Sorted unique output
      • Maps

      • Queues, Stacks & Priority Queues

        • Queues: first in, first out: First in, first out, ArrayDeque or LinkedList as a queue, offer/poll/peek vs add/remove/element, Processing loops and round robin
        • Stacks with ArrayDeque: push, pop and peek, Why not the old Stack class, An undo history, A balanced-brackets checker
        • Deque: both ends: The First and Last method families, Queue and stack methods on a Deque, The push/offer mixing trap, Palindromes and the sliding window maximum
        • PriorityQueue: always the smallest first: The min-heap and why printing is not sorted, A max-heap with reverseOrder, Hospital triage with a tie-breaker, Top k values with a size-k heap
        • Common mistakes and practice: Choosing by what comes out next, The null-unboxing crash from poll(), Breadth-first search with a queue, Classic problems: two-stack queue, monotonic stack, k-way merge
        • Must-do problems: Queues and Stacks: Stacks: brackets and reversing, Queues: simulations, Deque: sliding window, PriorityQueue: top K
      • Utilities & Best Practices

        • The Collections utility class: Collection vs Collections, Reorder with sort, reverse, swap, rotate and shuffle, Find with max, min, frequency and disjoint, Unmodifiable views vs frozen copies
        • Immutable collections: List.of, Set.of, Map.of: List.of, Set.of, Map.of, copyOf, Unmodifiable view vs immutable copy, UnsupportedOperationException
        • Moving between arrays and collections: Arrays.asList: a fixed-size view that writes through, Making your own list or a read-only copy, The int[] trap and toArray(new String[0]), Arrays.sort vs Collections.sort
        • equals and hashCode in collections: Which method each collection calls, equals without hashCode breaks hash collections, The lost-key bug after changing a key, TreeSet comparators that drop items; records as safe keys
        • Performance and choosing well: Big-O with real numbers, including amortized O(1), Counting steps exactly, Timing code honestly with System.nanoTime, Fixing hidden O(n²) loops and comparing the main collections
        • Collections interview questions and practice: Choosing a collection with four questions, Classic output traps: remove(int), Integer == and PriorityQueue printing, Fail-fast iterators and safe removal, Classic problems: counting, pair-sum and LRU cache
      • Collections Mini Projects

        • Student Gradebook: Store student records in an ArrayList, Sort a copy with comparingInt, reversed and thenComparing, Remove by index safely, Class statistics with Collections.max/min and a TreeMap
        • Word Frequency Analyzer: Count words with HashMap.merge, Skip stop words with Set.of, List words A to Z with a TreeMap, Find the top N words with a PriorityQueue
        • Contact Book: Key a TreeMap by lower-case name, Block duplicate names and numbers, Search by prefix with tailMap, Group contacts by tag with computeIfAbsent
        • Task Scheduler: Order tasks with a PriorityQueue and an enum priority, Plan the day with a first-in-first-out Queue, Undo with an ArrayDeque used as a stack, Print a PriorityQueue in order by sorting a copy
        • Library System with Collections: Look up books and members by id in maps, Track issued books with sets, Keep a waiting queue per book, Print sorted reports with Comparator chains
  2. Stage 2: Master DSA

    Become a confident problem solver

    • Problem Solving & Coding Patterns
    • Data Structures & Algorithms in Java
    • Coding Challenges
    See this stage
    See all topics in Master DSA
    1. Problem Solving & Coding Patterns

      A repeatable way to solve problems: complexity, recursion and the common patterns behind most coding questions.

      • How to Approach a Problem

        • What problem solving really means: What a coding problem asks: input, output and rules, Why typing code first usually fails, The five-step routine used in this section, Where the same routine shows up at work: bug fixes and new features
        • Restate the problem and make examples: Restating a problem in your own words, Writing small examples by hand, Finding hidden questions: sorted? duplicates? value range?, Asking clarifying questions the way interviews expect
        • Start with brute force: What brute force means, Trying every option with loops, Why a correct slow answer is still valuable, Saying why the brute force is slow
        • Dry run on paper: Tracing variables in a table, Tracing loops step by step, Catching bugs before you run anything, Dry running someone else's code
        • The edge case checklist: Empty input and a single element, Duplicates, negatives and zeros, Smallest and largest allowed values, Writing edge cases before writing code
        • From brute force to optimal: Finding the repeated work, Trading memory for speed, Sorting first or using a set, Worked walk-through: pair with a given sum
        • Practice: the full routine: Five problems solved end to end, Writing the plan as comments first, A self-check rubric
      • Time & Space Complexity

        • Why we measure speed: Same answer, very different speed, Counting steps instead of seconds, Input size n, Real cost of slow code: timeouts, slow pages, server bills
        • Big O notation: Growth rates: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ), Dropping constants and smaller terms, Reading a growth chart, Big O as an upper bound (simplified model)
        • Counting work in loops: Single loops, Nested loops, Dependent loops where j starts from i, Loops one after another versus nested
        • Halving loops and log n: Where log n comes from, Loops that double or halve, log₂ of 10^9 is about 30, A first look at binary search
        • Space complexity: Extra memory versus input memory, Arrays, maps and copies, The call stack in recursion, In-place algorithms
        • Best, average and worst case: Best and worst case of linear search, Why interviews ask for the worst case, Amortised cost: ArrayList add (simplified), Hidden costs in library calls: contains, substring, string +
        • From constraints to a target complexity: About 10^8 simple steps per second (rule of thumb, not a law), What fits for n ≤ 20, 10^3, 10^5 and 10^6, Picking an approach from the limits, When constant factors matter
        • Practice: analyse real code: Ten snippets to analyse, Comparing two solutions to one problem, Explaining your answer interview-style
      • Testing Your Solutions

      • Array & String Techniques

        • Array traversal patterns: Forward, backward and step loops, Running max, min and sum, Counting with conditions, Index bugs to avoid
        • Dynamic arrays: how ArrayList grows: Fixed-size arrays versus growable lists, Build your own dynamic array: add, get, remove, Doubling the capacity and copying, Why add is amortised O(1) and remove from the front is O(n)
        • Reverse and rotate in place: Swapping with a temp variable, Reversing a range, Rotating by k with three reversals, When k is larger than n
        • Counting with arrays: int[26] for lowercase letters, Counting digits and other small ranges, Valid anagram, First unique character
        • Maximum subarray: Kadane's algorithm: Brute force over all subarrays, Extend the current run or start fresh, All-negative arrays, Returning the subarray itself
        • Matrix traversal: Row and column loops, Transpose and rotate by 90 degrees, Spiral order, Diagonals, Real world: images as grids of pixels
        • Building strings efficiently: Why String + in a loop is slow, StringBuilder append, insert and reverse, char arrays for in-place edits, Palindrome checks
        • Parsing and cleaning text: split, trim and simple regular expressions, Character class methods, Reverse the words in a sentence, Real world: cleaning user input and CSV lines
        • Simulation problems: Following rules step by step, Keeping state in variables, Game-of-life style grids, Testing a simulation
        • Practice: arrays and strings: Second largest element and leaders in an array, Rotate a matrix and spiral order, Longest common prefix and string compression, Product of array except self, Stating time and space for each answer
      • Two Pointers

        • The two pointers idea: One loop instead of two, Pointers from both ends versus the same direction, When the data must be sorted
        • Pair sum in a sorted array: Move left or right by comparing, Why no valid pair is skipped (proof sketch), Counting all pairs, Handling duplicates
        • Read and write pointers: Remove duplicates in place, Move zeros to the end, Remove a given value, Keeping the original order
        • Merging two sorted arrays: Merging into a new array, Merging in place from the end, Intersection and union of sorted arrays, Real world: merging sorted log files
        • Palindromes with two pointers: Valid palindrome ignoring symbols, Palindrome after deleting one character, Reverse only the vowels
        • Container with most water: The area formula, Why we move the shorter side, Trapping rain water with two pointers
        • Three sum and k-sum: Sort, then fix one number, Skipping duplicates, Three sum closest, The k-sum idea
        • Dutch national flag: Three regions with three pointers, Sorting 0s, 1s and 2s in one pass, Partitioning around a pivot
        • Practice: two pointers: Squares of a sorted array, Remove duplicates allowing two copies, Four sum and three sum closest, Boats to save people, When two pointers fails: unsorted data with no order to use
      • Sliding Window

      • Prefix Sums & Hashing

        • Prefix sum arrays: Running totals, Range sum in O(1), Avoiding off-by-one with size n + 1
        • 2D prefix sums: Sum of a sub-rectangle, Inclusion and exclusion, Real world: summing regions of an image
        • Difference arrays: Range add in O(1), Rebuilding values with a prefix sum, Real world: bookings per day
        • HashMap and HashSet patterns: Frequency counting, Seen-before checks, Two sum with a map, Grouping anagrams
        • Subarray sum equals k: Prefix sums plus a map of counts, Why the map starts with 0, Works with negative numbers, Subarrays divisible by k
        • Longest subarray with a given sum: Storing only the first index, Zero-sum subarrays, Equal numbers of 0s and 1s
        • Longest consecutive sequence: Set lookups, Starting only at the start of a run, Why it is O(n)
        • Hashing pitfalls in Java: == on boxed Integer values, Mutable keys, Many collisions slow a map down (simplified), Using an array when the range is small
        • Practice: prefix sums and hashing: Range sum query and equilibrium index, Contiguous array with equal 0s and 1s, Group anagrams and top k frequent words, Count of subarrays with XOR equal to k, Choosing prefix sums, a map or both
      • Binary Search

        • How binary search works: Halving a sorted range, The guess-the-number game, Only about log n steps
        • Classic binary search in Java: lo, hi and the loop condition, A safe mid: lo + (hi − lo) / 2, Iterative versus recursive, Arrays.binarySearch and its negative result
        • First and last position: Lower bound and upper bound, First and last occurrence, Counting a value, Insert position
        • Rotated arrays and peaks: Search in a rotated sorted array, Minimum of a rotated array, Finding a peak element
        • Searching a sorted matrix: Treating the matrix as one flat array, Staircase search from a corner, Choosing between the two
        • Binary search on the answer: A monotonic yes/no condition, Minimum ship capacity, Koko eating bananas, Integer square root
        • Advanced binary search: Split array largest sum, Aggressive cows, Median of two sorted arrays (idea), Real world: git bisect finds the commit that broke a build
        • Ternary search: Unimodal functions: one peak or one valley, Splitting the range in three, Ternary search on integers and on doubles, When binary search on the slope is simpler
        • Practice: binary search: Search insert position and count of occurrences, Find minimum in a rotated array with duplicates, Capacity to ship packages and book allocation, Nth root of a number, An off-by-one checklist for every binary search
      • Recursion in Depth

        • Recursion refresher: Base case and recursive step, What lives on the call stack, Pre-work vs post-work around the call, Leap of faith: trusting the smaller call
        • Recursion trees: A chain tree for factorial, A binary tree for Fibonacci, Counting nodes and levels, Why recursion trees give you time and space
        • Recursion on arrays and strings: Passing an index instead of slicing, Sum, max and isSorted on an array, Reverse a string and check a palindrome, Returning a result vs filling an answer list
        • Several recursive calls: Fibonacci and why it repeats work, Climbing stairs and grid paths, Tower of Hanoi step by step, A first look at memoization
        • Divide and conquer: Split, solve, combine, Fast power a^n in O(log n), Max of an array by splitting in halves, Where divide and conquer leads next (merge sort, quick sort)
        • The cost of recursive code: Work per call times number of calls, Four recurrences you will meet everywhere, Stack space equals maximum depth, Extra heap space inside recursive calls
        • Recursion depth and StackOverflowError: How deep Java's call stack can go, Why Java does not optimize tail calls, Rewriting tail recursion as a while loop, Using your own Deque stack when recursion is too deep
        • Practice: recursion: Sum of digits and digital root, Power of two / three using recursion, Remove adjacent duplicates recursively, K-th symbol in grammar, Josephus problem, Tracing tricky recursive outputs
      • Backtracking

        • What backtracking is: Choices, constraints and goal, Choose, explore, un-choose, The state space tree
        • Generating subsets: Include or exclude, The loop-based version, Subsets with duplicates, Bitmask version preview
        • Generating permutations: Using a used[] array, The swap method, Permutations with duplicates
        • Combinations and combination sum: Choosing k of n, Combination sum with reuse, Combination sum without reuse, Sorting to prune
        • Backtracking on grids: Word search, Rat in a maze, Marking and unmarking visited cells
        • N-Queens and Sudoku: Safe placement checks, Sets for columns and diagonals, A Sudoku solver
        • Pruning the search: Stopping early with bounds, Ordering choices, Cost with and without pruning, Real world: puzzle solvers and timetable builders
        • Practice: backtracking: Generate valid parentheses, Letter combinations of a phone number, Palindrome partitioning, Partition to k equal sum subsets, Reusing one template
      • Bit Manipulation & Math Basics

        • Binary numbers: Binary and decimal conversion, Signed integers and two's complement, Integer.toBinaryString
        • Bitwise operators: &, |, ^, ~, Left and right shifts <<, >>, >>>, Common operator precedence bugs
        • Common bit tricks: Check, set, clear and toggle the k-th bit, Count set bits with n & (n - 1), Check if a number is a power of two, Lowest set bit with n & -n
        • XOR tricks and bitmasks: Single number, Missing number, Swapping without a temp, and why not to, Real world: flags and permissions as bitmasks
        • GCD and LCM: Euclid's method, LCM without overflow, Real world: when repeating schedules line up
        • Primes and the sieve: Trial division up to √n, Sieve of Eratosthenes, Prime factorisation
        • Modular arithmetic: Why 1_000_000_007, Add, subtract and multiply under a mod, Negative results of % in Java, Fast modular power
        • Counting: nCr, Pascal and modular inverse: Permutations and combinations by formula, Pascal's triangle for nCr, Precomputed factorials for nCr modulo a prime, Modular inverse with Fermat's little theorem, Counting questions from placement tests
        • Overflow and big numbers: int and long limits, Math.addExact and Math.multiplyExact, BigInteger when long is not enough
        • Practice: bits and math: Count primes up to n, Power set with bitmasks, Single number II and III, Divide two integers without / and *, nCr modulo 1e9+7
      • Pattern Practice

        • Spotting the pattern: Clue words for each pattern, Constraints as clues, A decision flowchart
        • Mixed set: easy: Ten unlabelled easy problems, Brute force first, then optimal, Naming the pattern before coding, Self-review with the routine checklist
        • Mixed set: medium: Ten unlabelled medium problems, Complexity and tests for every answer, Comparing your answer with a model solution, Logging which pattern you missed
        • Mixed set: hard: Six problems that combine two patterns, Getting a partial solution first, Writing the plan before the code, Reviewing the model solution step by step
        • Your pattern notes: One page per pattern, Templates and common bugs, A spaced revision plan
        • Patterns checkpoint: Timed checkpoint test, Scoring yourself, Where to go back
    2. Data Structures & Algorithms in Java

      Linked lists, stacks, queues, trees, heaps, tries, graphs, sorting, greedy algorithms and dynamic programming, built and used in Java.

      • Linked Lists

        • Why linked lists exist: Arrays versus nodes in memory, A Node class with next, Cost of insert and access, Java's LinkedList versus your own
        • Build a singly linked list: Add first and add last, Traverse and print, Search, Tracking the size
        • Insert and delete nodes: Insert at a position, Delete by value and by position, The dummy head node, Null pointer traps
        • Reverse a linked list: Three-pointer iterative reverse, Recursive reverse, Reverse a sublist, Reverse in groups of k
        • Fast and slow pointers: Middle node, Cycle detection with Floyd's method, Start of the cycle, Palindrome linked list
        • Merge and remove problems: Merge two sorted lists, Remove the nth node from the end, Remove duplicates, Intersection of two lists
        • Doubly and circular linked lists: prev and next links, O(1) insert and delete when you hold the node, Circular lists, Real world: browser back and forward
        • Design an LRU cache: HashMap plus a doubly linked list, get and put in O(1), LinkedHashMap with access order, Real world: caches in browsers and servers
        • Advanced list problems: Copy a list with random pointers, Add two numbers, Sort a list with merge sort, Flatten a multilevel list
        • Practice: linked lists: Odd-even linked list, Rotate a list by k, Remove all occurrences of a value, Reorder list, Drawing pointers before coding
      • Stacks & Queues

      • Hash Tables from Scratch

        • How hashing works: From key to index with a hash function, Buckets, Why lookup is O(1) on average
        • Build a hash map with chaining: An array of linked lists, put, get and remove, Deciding about null keys
        • Open addressing: Linear probing, Deleting with tombstones, Clustering
        • Load factor and resizing: Why a map resizes, The cost of rehashing, Amortised O(1)
        • Inside Java's HashMap: Buckets and tree bins (Java 8 and later), How hashCode is spread, Iteration order is not guaranteed, A simplified model, labelled as one
        • hashCode and equals in practice: The contract, recapped, Bad hash functions and slow maps, Records as keys
        • Hashing in the real world: Removing duplicates, Checksums and file integrity, Hashing is not encryption, A first look at consistent hashing
        • Practice: hash tables: Design a HashSet without libraries, Design a HashMap without libraries, Find duplicate files by content, Isomorphic strings and word pattern, Testing your own map with many keys
      • Sorting Algorithms

        • Why sorting matters: Sorted data enables binary search and two pointers, Comparison sorts, Stability, Real world: leaderboards and reports
        • Bubble, selection and insertion sort: Each traced by hand, Code for each, When insertion sort is a good choice
        • Merge sort: Divide, sort, merge, O(n log n) time and O(n) space, Merge sort is stable
        • Counting inversions: What an inversion is, Counting during the merge, Real world: how similar two rankings are
        • Quick sort: Lomuto and Hoare partition, Choosing a pivot, Worst case O(n²), Random pivots
        • Quickselect: kth largest in average O(n), Why the worst case is O(n²) and how random pivots help, Quickselect versus a heap
        • Counting and radix sort: Counting sort for small ranges, The radix sort idea, The bucket sort idea, Why comparison sorts need about n log n
        • How Java sorts: Arrays.sort for primitives (dual-pivot quicksort), Arrays.sort for objects (TimSort, stable), Collections.sort and List.sort, Comparators, recapped
        • Problems solved by sorting first: Overlapping meetings, Largest number from digits, Custom sort orders
        • Practice: sorting: Sort colours and wiggle sort, Sort characters by frequency, Minimum swaps to sort, Merge sorted arrays in place, Picking a sort for the data
      • Binary Trees

      • Binary Search Trees

        • The BST rule: Smaller on the left, larger on the right, Searching a BST, Cost depends on height
        • Insert into a BST: Recursive insert, Iterative insert, A policy for duplicates, Building a BST from a list of values
        • Delete from a BST: Deleting a leaf, Deleting a node with one child, Deleting a node with two children, The inorder successor
        • Validate a BST: The common wrong check, Min and max bounds, The inorder check
        • Using sorted order: kth smallest element, A BST iterator, Two sum in a BST
        • Floor, ceiling and LCA in a BST: Floor and ceiling search, LCA using values, Range queries
        • Why balance matters: Skewed trees, The idea of rotations, AVL and red-black trees at a glance (simplified), TreeMap and TreeSet use red-black trees
        • Build a balanced BST: Sorted array to a balanced BST, Sorted linked list to a BST, Rebalancing any BST through its inorder list
        • TreeMap in problem solving: floorKey, ceilingKey and subMap, Calendar booking, Real world: price ladders and time-based lookups
        • Practice: BSTs: Recover a BST with two swapped nodes, Largest BST inside a binary tree, Trim a BST to a range, Convert a BST to a greater tree, BST versus hashing for the task
      • Heaps & Tries

        • What a heap is: Min heap and max heap, A complete tree stored in an array, Parent and child indexes
        • Build a heap yourself: Sift up on insert, Sift down on remove, Heapify in O(n)
        • Heap sort: Building a max heap in place, Repeatedly moving the max to the end, O(n log n) time, O(1) extra space, not stable
        • PriorityQueue in Java: A min heap by default, A max heap with a comparator, Custom objects, Iteration is not in sorted order
        • Top k problems: kth largest with a size-k heap, Top k frequent elements, K closest points, Merge k sorted lists
        • Two heaps: running median: Balancing a max heap and a min heap, Median of a stream, Real world: live statistics
        • Scheduling with heaps: Task scheduler, Meeting rooms with a heap, Real world: job schedulers
        • Tries: A node with children, insert, search and startsWith, Array versus map children
        • Trie applications: Autocomplete, Word search II, Longest common prefix, Real world: search suggestions
        • Practice: heaps and tries: Reorganise a string, Kth smallest in a sorted matrix, Maximum XOR of two numbers with a bit trie, Replace words with a trie, Explaining your choice of structure
      • Graphs: Basics & Traversal

        • What a graph is: Vertices and edges, Directed, undirected and weighted, Real world: maps, social networks and dependencies
        • Storing graphs in Java: Adjacency matrix, Adjacency list with List<List<Integer>>, Edge list, Choosing one
        • Breadth-first search: A queue and a visited array, Levels and distances, Tracing by hand
        • Depth-first search: Recursive DFS, Iterative DFS with a stack, Visit order
        • Connected components: Counting components, Component sizes, Friend circles
        • Grids as graphs: Direction arrays, Number of islands, Flood fill, Boundary checks
        • Cycle detection: Undirected graphs with a parent, Directed graphs with three colours, Real world: circular dependencies
        • Bipartite graphs: Two-colouring with BFS, Two-colouring with DFS, Odd cycles make a graph not bipartite, Real world: splitting people into two teams
        • Practice: graph traversal: Surrounded regions, Number of enclaves, Clone a graph, Number of distinct islands, Choosing BFS or DFS
      • Graph Algorithms

        • Shortest path with BFS: Unweighted shortest paths, Rebuilding the path, Word ladder
        • Multi-source BFS: Many starting points, Rotting oranges, Distance to the nearest cell
        • 0-1 BFS: Edges of weight 0 or 1, A deque instead of a priority queue, Minimum cost to make a valid grid path
        • Dijkstra algorithm: Greedy with a PriorityQueue, Skipping stale entries, No negative edges, Real world: map routing
        • Topological sort: Kahn's algorithm, DFS finishing order, Course schedule, Real world: build tools ordering tasks
        • Disjoint set union: find and union, Path compression and union by rank, Nearly O(1) per operation, Real world: network connectivity
        • Minimum spanning trees: Kruskal with union-find, Prim with a heap, Real world: laying cable at the least cost
        • Graph algorithms practice: Network delay time, Path with minimum effort, Number of provinces with union-find, Accounts merge, Alien dictionary
      • Advanced Graph Algorithms

        • Bellman-Ford: Relaxing every edge n − 1 times, Negative edges, Detecting negative cycles, Cheapest flights within k stops
        • Floyd-Warshall: All-pairs shortest paths, O(n³) and when it fits, Transitive closure
        • Shortest and longest paths in a DAG: Topological order, then relax, Longest path, Real world: the critical path of a project
        • Graphs hidden in problems: States as nodes, BFS over states: open the lock, Bitmask states, Real world: puzzle and game solvers
        • Strongly connected components: Kosaraju's algorithm, The idea of Tarjan's algorithm, The condensation graph
        • Bridges and articulation points: Discovery and low times, Critical connections, Real world: single points of failure in a network
        • Euler paths and circuits: Using every edge exactly once, Degree rules for paths and circuits, Hierholzer's algorithm, Reconstruct an itinerary
        • Maximum flow and matching (overview): Networks, capacities and flow, The augmenting path idea (Ford-Fulkerson, Edmonds-Karp), Max-flow equals min-cut, Bipartite matching as a flow problem, Real world: assigning people to jobs
        • Practice: advanced graphs: Cheapest flights within k stops, City with the fewest reachable neighbours, Critical connections in a network, Minimum moves in a sliding puzzle, Choosing the algorithm from the constraints
      • Greedy Algorithms & Intervals

        • What greedy means: The best local choice, A counter-example where greedy fails, The exchange argument (simplified)
        • Activity selection: Sort by end time, Maximum meetings in one room, Minimum arrows to burst balloons
        • Merge and insert intervals: Sort by start, Merging overlaps, Inserting an interval, Interval intersections
        • Meeting rooms: Minimum rooms with sorting, Minimum rooms with a heap, The sweep line idea, Real world: calendar booking
        • Jump game and gas station: Farthest reach, Minimum number of jumps, Gas station: total and start
        • Greedy with heaps: Minimum cost to connect ropes, The Huffman coding idea, Choosing projects for maximum capital
        • Fractional knapsack and the limits of greedy: Fractional knapsack by value per weight, Why 0/1 knapsack needs DP, A coin change counter-example
        • Practice: greedy and intervals: Assign cookies and lemonade change, Non-overlapping intervals, Candy distribution, Partition labels, Proving or disproving a greedy idea
      • Dynamic Programming (1D)

        • What dynamic programming is: Optimal substructure, Overlapping subproblems, Memoization vs tabulation overview
        • Memoization: Recursion tree pruning, Memoization table design, Call stack overhead
        • Tabulation: Base cases and table initialization, Iteration order and state dependencies, Comparing tabulation to memoization
        • The DP recipe: State definition and meaning, Recurrence relation formulation, Complexity analysis and space reduction
        • Climbing stairs and house robber: Climbing stairs variations, House robber non-adjacent recurrence, Rolling variable space optimization
        • Coin change: Minimum coins optimization, Number of combinations counting, Permutations versus combinations iteration order
        • Decode ways and word break: Decode ways single and double digit lookback, Word break substring segmentation, Prefix lookback optimization
        • Longest increasing subsequence: Quadratic LIS dynamic programming, Path reconstruction via parent pointers, Binary search patience sorting acceleration
        • Saving space in DP: Rolling variables for fixed lookback, Circular arrays for k-step lookback, 1D compression for 2D tables
        • Best Time to Buy and Sell Stock: Single trade and unlimited trades, State machine transition modeling, Cooldown and transaction fee variations
        • 1D Dynamic Programming Practice: Pattern recognition in 1D DP, Dual state tracking for maximum product subarray, Counting combinations and optimal paths, Sliding window and lookback optimizations
      • Dynamic Programming: 2D & Common Families

        • Grid paths: Unique paths, Paths with obstacles, Minimum path sum, Triangle
        • 0/1 knapsack: Take or skip, The 2D table, One row with a reverse loop, Real world: choosing items within a budget
        • The subset sum family: Subset sum, Equal partition, Target sum, Counting subsets
        • Unbounded knapsack: Reusing items, Rod cutting, The forward loop
        • Longest common subsequence: The LCS table, Printing the LCS, Real world: diff tools and DNA comparison
        • Edit distance: Insert, delete and replace, Walking through the table, Real world: spell checkers and fuzzy search
        • Palindrome DP: Longest palindromic substring, Longest palindromic subsequence, Palindrome partitioning
        • Solving a new DP problem: Recognising the family, From recursion to a table, Common mistakes
        • Practice: 2D DP: Minimum falling path sum, Cherry pickup with two walkers, Distinct subsequences, Wildcard matching, Stating time and space
      • Advanced Dynamic Programming

      • String Algorithms

        • Searching text: indexOf and contains in Java, The cost of naive string search, Real world: find in an editor
        • Rolling hash and Rabin-Karp: Polynomial hashing, Rolling the hash forward, Collisions and double hashing, Repeated substrings
        • The KMP algorithm: The prefix function (LPS array), Searching in O(n + m), The shortest palindrome trick
        • The Z-algorithm: The Z array, Pattern search with a separator, Z versus KMP
        • Palindrome algorithms: Expand around centre, The idea of Manacher's algorithm (overview), Counting palindromic substrings
        • Practice: string algorithms: Find the index of the first occurrence, Repeated string match, Longest happy prefix, Longest duplicate substring, Choosing between KMP, Z and hashing
      • Advanced Data Structures

      • DSA Problem Sets

    3. Coding Challenges

      Coding problems for every topic taught in Stage 2, in the same order and graded easy, medium and hard, with test cases, step-by-step hints and model solutions.

  3. Stage 3: Master Java

    Develop strong core Java skills

    • Streams & Modern Java
    • Files, I/O & Robust Error Handling
    • Multithreading & Concurrency
    • JVM Internals & Memory Management
    See this stage
    See all topics in Master Java
    1. Streams & Modern Java

      The Stream API, Optional, method references, the Date and Time API and other modern Java features used in real code and interviews.

      • Functional Interfaces in Practice

        • The java.util.function package: Recap: a functional interface has one abstract method and a lambda fills it in, Why Java ships ready-made interfaces instead of one per task, The four core shapes: takes and returns, takes and tests, takes only, returns only, Where you already meet them: removeIf, forEach and computeIfAbsent
        • Function and Predicate: Function<T, R> and apply: marks to grade, rupees to paise, Predicate<T> and test: is the phone number 10 digits, did the student pass, Passing behaviour into a method: filterStudents(list, rule), Common mistake: forgetting the generic types and getting Object back
        • Consumer and Supplier: Consumer<T> and accept: printing or logging each item, Supplier<T> and get: default values, ID and OTP generators, Lazy work with Supplier: the value is made only when get is called, Trap: a Supplier runs again on every get call
        • BiFunction, UnaryOperator and BinaryOperator: BiFunction, BiPredicate and BiConsumer for two inputs, with Map.forEach, UnaryOperator<T> as a Function with the same input and output type, with List.replaceAll, BinaryOperator<T> for combining two values, with Map.merge for word counts, BinaryOperator.minBy and maxBy with a Comparator, Choosing the most specific interface so the code explains itself
        • Primitive functional interfaces: Why boxing int to Integer costs time and memory in large loops, IntPredicate, IntFunction, IntUnaryOperator and IntBinaryOperator, ToIntFunction and ToDoubleFunction, as used by Comparator.comparingInt, Reading the naming pattern: Int..., To...Function, ObjIntConsumer, Common mistake: mixing Predicate<Integer> and IntPredicate in one call
        • Combine functions and predicates: Function.andThen versus compose and the order trap, Function.identity and when it is useful, Predicate and, or, negate and Predicate.not, Consumer.andThen for running two actions in turn, Real-world use: building loan or scholarship eligibility rules from small predicates
        • Effectively final variables in lambdas: What effectively final means and how the compiler checks it, The error "local variables referenced from a lambda expression must be final or effectively final", Why lambdas capture values, not variables, Fields and this inside a lambda versus inside an anonymous class, Trap: the one-element array counter workaround and why it causes bugs
        • Write your own functional interface: When the built-in interfaces do not fit: three inputs or a checked exception, The @FunctionalInterface annotation and the compiler error it gives, Adding default methods to your own interface for chaining, Checked exceptions inside lambdas: why Function cannot throw IOException, Interview point: is Comparator a functional interface even with many methods
        • Functional interfaces: mistakes and practice: Mixed exercises across all functional interfaces in the module, Fix the wrong interface choice and the wrong generic types, Build a validation rule set for a student registration form, Common mistakes: compose order, boxing, capturing a changing variable
      • Method References in Depth

        • What is a method reference?: The :: symbol as a short form of a lambda that only calls one method, The four kinds at a glance in one table, How the compiler matches a method reference to a functional interface, Same task written as a lambda and as a method reference
        • Static method references: Integer::parseInt, Math::max and String::valueOf, Referencing your own utility method, such as GradeUtils::gradeFor, Matching parameters: Function, BinaryOperator and Comparator, Trap: overloaded methods that make a reference ambiguous
        • Bound instance references: System.out::println: the object is fixed before the call, object::method and this::method inside a class, Real-world use: validator::isValid or logger::info passed into a pipeline, Trap: the receiver is evaluated once, so a null receiver fails immediately
        • Unbound instance references: String::length and String::toUpperCase: the first argument becomes the object, Two-argument forms: String::compareToIgnoreCase as a Comparator, Record accessors and getters with Comparator.comparing(Student::marks), Interview point: how String::length and str::length differ
        • Constructor references: ArrayList::new and HashMap::new as a Supplier, Student::new with Function and BiFunction: which constructor is chosen, Array constructor references: String[]::new and int[]::new, Map factories like TreeMap::new, used later with collectors
        • Lambda or method reference?: Readability rules: use a reference when the method name says it all, When a lambda is clearer: extra arguments, two steps, or a condition, Reading stack traces and errors that involve method references, Common mistakes: calling the method with brackets, wrong argument order, Interview point: are method references faster than lambdas
        • Method references: practice: Convert a set of lambdas to the right kind of method reference, Sort a contact list with chained Comparator references, Build objects from text input with constructor references, Find the lambdas that should stay lambdas
      • Stream Basics

        • What is a stream?: A stream is a flow of values, not a place to store them, Saying what you want instead of how to loop, A first pipeline: count students who scored above 60, The same task as a for loop and as a stream
        • Create streams from data: list.stream() and set.stream() from collections, Arrays.stream and Stream.of, plus Stream.empty and Stream.ofNullable, Streams from a map with entrySet().stream(), Streams from text: String.lines and String.chars, Trap: Stream.of(intArray) gives one element, not many
        • Source, intermediate and terminal operations: The three parts of every pipeline, Intermediate operations return a stream; terminal operations return a result, Nothing runs until a terminal operation is called, Formatting long pipelines one step per line
        • Lazy evaluation and element flow: Each element passes through the whole pipeline before the next one starts, Tracing a pipeline with print statements to see the real order, Short-circuiting: findFirst and limit stop the work early, Why laziness saves work on large data such as server logs
        • A stream can be used only once: The error "stream has already been operated upon or closed", Trap: storing a stream in a variable and using it twice, Supplier<Stream<T>> to build a fresh stream when needed, A stream never changes its source collection, ConcurrentModificationException when a lambda changes the source list
        • Loops versus streams: Same tasks both ways: total fees, names of toppers, filter and transform, When a loop is still better: index access, complex early exit, checked exceptions, Readability: a short pipeline versus a nested loop, Interview point: are streams faster than loops
        • Stream basics: practice: Predict the output and order of small pipelines, Fix a stream used twice and a pipeline with no terminal operation, Rewrite attendance loops as streams, Mixed exercises on creating streams from different sources
      • Transforming Streams

        • Keep elements with filter: filter with a Predicate: keep only passing students, Several filters versus one combined condition, Predicate.not and reusable named predicates, Real-world use: keep only failed UPI transactions from a log, Trap: null elements inside the list
        • Change elements with map: map turns each element into a new value, Changing type: Stream<Student> to Stream<String>, Chaining map with filter in a readable order, Trap: using map for side effects such as printing
        • Flatten nested data with flatMap: The problem: a List<List<String>> of subjects per student, flatMap turns each element into a stream and joins them, Splitting lines into words for a word count, Trap: map giving Stream<Stream<T>> instead of a flat stream, Interview point: map versus flatMap
        • distinct and sorted: distinct uses equals and hashCode, so records work out of the box, sorted in natural order and with a Comparator, Comparator.comparing, thenComparing and reversed in a pipeline, sorted needs all elements first: what stateful means, Trap: reversed after a lambda comparator loses the type
        • limit and skip: Top N results: sort, then limit, Paging with skip and limit, as in an API that returns page 3 of results, Order matters: skip then limit versus limit then skip, Trap: limit before sorted gives the wrong top N
        • takeWhile and dropWhile: takeWhile stops at the first element that fails, dropWhile skips until the first element that fails, How they differ from filter, shown side by side, Real-world use: read log lines until the first ERROR, Trap: using them on unsorted data
        • peek for debugging only: peek lets you look at elements as they pass, Using peek to see laziness and element flow, Why peek must not hold real logic: it may not run at all, for example before count, Removing debug peeks before code review
        • Build clean multi-step pipelines: Ordering steps for speed: filter before map, before sorted, Pulling long lambdas out into named methods and predicates, mapMulti (Java 16) as an alternative to flatMap, Real-world use: turning raw order records into a dashboard list
        • Transforming streams: practice: Mixed exercises with filter, map, flatMap, distinct and sorted, Page through a product list with skip and limit, Fix pipelines with the wrong step order, Trace takeWhile and dropWhile outputs
      • Terminal Operations & Reduction

        • forEach and count: forEach to act on each element, and forEachOrdered, count to get the number of elements as a long, Iterable.forEach versus stream().forEach, Trap: adding to an outside list inside forEach instead of collecting
        • min and max with a Comparator: min and max need a Comparator, Comparator.comparing for the topper or the cheapest product, Why the result is an Optional, Ties: which element wins when two are equal
        • anyMatch, allMatch and noneMatch: Three yes or no checks over a stream, Short-circuiting: they stop as soon as the answer is known, Real-world use: did every payment in a batch succeed, Trap: allMatch on an empty stream returns true
        • findFirst and findAny: findFirst after filter: the first student from a branch, findAny and why it may return a different element in parallel streams, Handling the Optional result safely, Interview point: findFirst versus findAny
        • reduce with an identity: Combining all elements into one value: total, product, longest name, Identity and accumulator, traced step by step, reduce versus sum for numbers, Trap: an identity that is not neutral, such as 1 for a sum
        • More forms of reduce: reduce without an identity returns an Optional, The three-argument reduce and its combiner for parallel streams, Trap: reducing into a mutable StringBuilder or list, When collect is the right tool instead of reduce
        • toList() versus collect(Collectors.toList()): Stream.toList() (Java 16) returns an unmodifiable list, Collectors.toList() and Collectors.toUnmodifiableList(), Trap: UnsupportedOperationException when adding to the result, toArray(String[]::new) for arrays, Interview point: which one to use and why
        • Terminal operations: practice: Mixed exercises with count, min, max, matches and find, Totals and best values with reduce, Fix an UnsupportedOperationException and a wrong identity, Validate a batch of exam results
      • Collectors

        • collect and the Collectors class: What collect does and what a collector is, toSet and toUnmodifiableSet, toCollection(TreeSet::new) for a chosen collection type, Choosing list, set or a specific collection for the result
        • toMap and duplicate keys: toMap with a key function and a value function: roll number to student, IllegalStateException on duplicate keys, A merge function to keep the first, the last or the sum, Map supplier argument for a TreeMap or LinkedHashMap, Trap: null values throw NullPointerException in toMap
        • Group data with groupingBy: groupingBy gives Map<K, List<V>>: students by branch, Records as composite keys, such as branch and year together, The default map is a HashMap with no fixed order, Real-world use: orders grouped by city for a dashboard
        • Downstream collectors: Passing a second collector into groupingBy, counting, summingInt and averagingDouble per group, maxBy and minBy per group: topper of each branch, mapping and toSet as downstream collectors, Real-world use: total sales per category
        • Summary statistics and teeing: summarizingInt and summarizingDouble, IntSummaryStatistics: count, sum, min, average and max in one pass, Collectors.teeing (Java 12) to combine two results, Real-world use: a marks summary card for a class
        • Split data with partitioningBy: partitioningBy splits into true and false groups, Both keys are always present, even when a group is empty, Downstream collectors with partitioningBy: pass and fail counts, Interview point: partitioningBy versus groupingBy
        • joining, mapping and filtering collectors: joining with a delimiter, prefix and suffix: a CSV line or a report header, mapping inside groupingBy: names of students per branch, filtering and flatMapping as downstream collectors (Java 9), collectingAndThen to make the result unmodifiable or pick one value
        • Sorted and nested grouping: TreeMap::new as the map supplier for sorted keys, LinkedHashMap to keep a chosen order, Sorting map entries by value with Map.Entry.comparingByValue, Two-level grouping: by city, then by category, Real-world use: a sorted month-wise sales report
        • Collectors: practice: Mixed exercises across toMap, groupingBy and partitioningBy, Build a branch-wise result report with counts and averages, Fix duplicate key errors and unordered output, Word frequency sorted by count
      • Primitive & Parallel Streams

        • IntStream, LongStream and DoubleStream: Why number streams exist: no boxing, mapToInt, mapToDouble and back with boxed and mapToObj, sum, average and max on number streams, OptionalDouble from average and how to read it
        • Number ranges with IntStream.range: range versus rangeClosed, Replacing simple counting loops, Using indexes with range over a list or array, Characters of a String with chars()
        • Stream.iterate and Stream.generate: Infinite streams with Stream.iterate and a seed, iterate with a stop condition (Java 9), Stream.generate with a Supplier: random OTPs or test data, Trap: an infinite stream without limit never ends
        • Side effects and why they break streams: What a side effect is: changing something outside the lambda, Stateless lambdas and why streams expect them, Trap: adding to an ArrayList from a stream gives wrong results in parallel, Replacing side effects with collect or reduce
        • Parallel streams: parallelStream and parallel: splitting the work across cores, The common ForkJoinPool shared by all parallel streams, Order: forEach versus forEachOrdered, findAny versus findFirst, Thread safety rules for lambdas in parallel streams
        • When parallel streams help and hurt: What makes parallel worth it: large data, cheap merging, a splittable source, ArrayList and arrays split well; LinkedList and iterate do not, Trap: blocking calls such as network requests inside parallel streams, Measuring simply with System.nanoTime and why one run can mislead, Interview point: should you make every stream parallel
        • Stream pitfalls, readability and performance: Streams versus loops: speed in practice and why readability usually decides, Pipeline length, naming and when to split a pipeline, Checked exceptions inside lambdas and the usual fixes, A checklist of the most common stream mistakes from this section
        • Primitive and parallel streams: practice: Number exercises with ranges, sums and averages, Generate sequences with iterate and generate, Fix a parallel stream with a shared list, Decide loop, stream or parallel stream for given tasks
      • Optional

        • Why Optional exists: Recap: null and NullPointerException, Optional as a box that may be empty, used as a return type, Optional.of, Optional.ofNullable and Optional.empty, Trap: Optional.of(null) throws NullPointerException
        • Read a value from an Optional: isPresent and isEmpty (Java 11), ifPresent and ifPresentOrElse (Java 9), Trap: calling get on an empty Optional, Real-world use: finding a student by roll number
        • orElse, orElseGet and orElseThrow: orElse for a ready default value, orElseGet: the default is built only when needed, Trap: orElse runs an expensive call such as a database lookup every time, orElseThrow and orElseThrow with a custom exception, Interview point: orElse versus orElseGet
        • map, flatMap and filter on Optional: map to change the value inside the box, filter to keep the value only if it passes a check, flatMap when the method already returns an Optional, or (Java 9) to try a second source, Replacing nested null checks: user to address to city
        • Optional results from streams: findFirst, min, max and reduce return Optional, OptionalInt and OptionalDouble from number streams, Optional.stream (Java 9) to drop empty results in a pipeline, Real-world use: the latest order of each customer
        • Where Optional belongs and where it does not: Good use: return types of lookup methods, Bad use: fields, method parameters and collections of Optional, Return an empty list, not an Optional of a list, Trap: returning null from a method that returns Optional, Interview point: the isPresent then get pattern and why it is avoided
        • Optional: practice: Mixed exercises: create, read, transform and default, Refactor nested null checks into an Optional chain, Fix get on empty and orElse with an expensive call, Design lookup methods for a library system
      • Date & Time API

        • Dates with LocalDate: LocalDate.now, LocalDate.of and parsing an ISO date, Reading parts: day of week, month length, leap year, Month is 1 to 12 here, and the Month enum, Trap: plusDays returns a new date and the old one does not change
        • LocalTime and LocalDateTime: LocalTime for clock times: class and exam slots, LocalDateTime for a date with a time, Combining with atTime and atDate, truncatedTo to drop seconds and nanoseconds
        • Compare and adjust dates: isBefore, isAfter and isEqual, plus, minus and with for changing parts, TemporalAdjusters: last day of the month, next Monday, Real-world use: fee due dates and late fee checks
        • Period and Duration: Period for years, months and days: age from date of birth, Duration for hours, minutes and seconds: exam length, ChronoUnit.DAYS.between for a plain day count, Trap: Period.getDays is not the total number of days, Real-world use: overdue days and fine for a library book
        • Instant, time zones and IST: Instant as a point on the UTC timeline, used in logs and APIs, ZoneId Asia/Kolkata and the +05:30 offset of Indian Standard Time, ZonedDateTime and converting a meeting time for a client abroad, Daylight saving time in other countries, Real-world rule: store in UTC, show in local time
        • Format and parse dates: DateTimeFormatter.ofPattern with dd-MM-yyyy and other common patterns, Built-in ISO formatters, Parsing user input and handling DateTimeParseException, Pattern traps: MM versus mm, yyyy versus YYYY, hh versus HH, Month names with a Locale
        • Old Date and Calendar classes: Why Date and Calendar are avoided: mutable, months from 0, confusing names, SimpleDateFormat is not thread-safe, Converting Date to Instant and java.sql.Date to LocalDate for old code, Clock for code that is easy to test
        • Date and time: practice: Mixed exercises on dates, times, periods and zones, Build an exam timetable printer with formatted dates, Fix a wrong pattern and an ignored plusDays result, Count working days between two dates
      • Records & Sealed Types in Practice

        • Records as data carriers in streams: Recap: what a record gives you for free, Turning CSV lines into records in a pipeline, equals and hashCode make records work with distinct and as map keys, Records as composite keys for groupingBy
        • Validation and factory methods in records: Compact constructors to validate and clean data, Static factory methods such as of and fromCsv, Defensive copies with List.copyOf for list components, Trap: a record holding a mutable list is not truly immutable
        • Nested and local records: Nested records: an Order with an Address and a list of items, Local records inside a method for in-between stream results, Records implementing interfaces such as Comparable, Real-world use: records as the shape of API request and response data
        • Sealed classes and permits: Why close a hierarchy: only known subtypes allowed, sealed and permits syntax, Rules: where permitted subclasses must live, The compiler error for a subclass that is not permitted
        • final, sealed and non-sealed subclasses: Every permitted subclass must choose final, sealed or non-sealed, Records are always final, so they fit naturally, non-sealed to reopen one branch on purpose, Interview point: sealed versus final versus abstract
        • Sealed interfaces with records: sealed interface Shape with Circle and Rectangle records, Payment methods: UPI, Card and NetBanking as a sealed family, Leaving out permits when all types are in the same file, Handling each type with instanceof patterns (recap)
        • Model results with sealed types: A Result type with Success and Failure records, Expected failures as values instead of error codes or exceptions, Modelling API responses and order states, Why the compiler can check that every case is handled
        • Records and sealed types: practice: Mixed exercises on records, factories and validation, Design a sealed hierarchy for notifications: SMS, email and push, Fix a mutable record component and a missing permit, Group records in a stream report
      • Pattern Matching & Newer Language Features

        • Pattern matching for instanceof: The old way: instanceof, then a cast, Pattern variables in instanceof (Java 16), Scope rules with && and with a negated check, Rewriting an equals method with a pattern
        • Type patterns in switch: Java 21: case Circle c -> inside a switch, Recap of arrow switch and switch expressions, Dominance: why a broad case before a narrow one is a compiler error, When default is still needed for types that are not sealed
        • Guards with when: Java 21: case Order o when o.total() > 500 ->, Ordering guarded and unguarded cases, Replacing long if-else chains: delivery charges by order type, Trap: a guarded case does not count toward exhaustiveness
        • Exhaustive switch and case null: Java 21: no default needed when a switch covers every sealed subtype, The compiler error when a new subtype is added: a safety net, case null and case null, default (Java 21), Interview point: why sealed types and switch work well together
        • Record patterns and deconstruction: Java 21: case Point(int x, int y) -> to take a record apart, Nested record patterns: an order with an address, var inside record patterns, Record patterns with instanceof, Real-world use: evaluating a small expression tree
        • var: local type inference: var (Java 10) for local variables, Where it helps: long generic types and for loops, Where it hides meaning: var result = service.process(), Rules: no fields, no null start value, no lambda without a target, var in lambda parameters (Java 11)
        • Text blocks for multi-line strings: Text blocks (Java 15) with triple quotes, How indentation is removed, Escapes: backslash at line end and \s, formatted for JSON, SQL and HTML templates, Trap: trailing spaces are removed
        • Sequenced collections: Java 21: SequencedCollection with getFirst, getLast, addFirst and reversed, Java 21: SequencedMap with firstEntry, lastEntry and pollLastEntry, LinkedHashSet and LinkedHashMap gain a defined first and last, Replacing list.get(list.size() - 1)
        • Handy Java 11 to 17 additions: String methods: isBlank, strip, repeat and lines (Java 11), Helpful NullPointerException messages (Java 14), Collection.toArray(String[]::new) and Files.readString (Java 11), Reading release notes to find what changed between versions
        • Modern Java features: practice: Mixed exercises on instanceof patterns, switch patterns and guards, Rewrite an if-else type check chain as an exhaustive switch (Java 21), Deconstruct nested records in a billing calculator, Fix var misuse, a text block indentation bug and a dominance error
      • Modern Java Mini Projects

        • Refactor a marks report to streams: Start from a loop-heavy student result program, Replace each loop with a pipeline and keep the output identical, Toppers, branch averages and pass percentage with collectors, Decide which loops should stay and explain why
        • Monthly sales report: Sale records loaded from CSV text in a text block, Totals per city and category with groupingBy and summingDouble, Top 3 products and best sales day with sorted, limit and Optional, Rupee formatting and a sorted report with TreeMap
        • Attendance and leave tracker: Attendance records with LocalDate and working days without weekends and holidays, Attendance percentage per student and the 75 percent rule, Leave requests with Period and overlap checks, Shortfall warnings with formatted dates
        • Order processing with sealed types: Payment types as a sealed interface of records: UPI, Card, Cash on delivery, Order states handled with an exhaustive switch (Java 21), Delivery charge and discount rules with when guards (Java 21), A Result type for failed orders and a summary report
        • Server log analyser: Parse log lines into records with an Instant timestamp and level, Errors per hour and per service with groupingBy, Show times in IST and find the busiest window, Optional for the first error after a given time, A summary dashboard printed with a text block template
    2. Files, I/O & Robust Error Handling

      Read and write files with java.nio, handle resources safely and design error handling that real applications can rely on.

      • Exceptions in Depth

        • The exception family tree: Throwable at the top of the tree, Error versus Exception, The RuntimeException branch, Where common exceptions such as NullPointerException and IOException sit
        • Checked and unchecked exceptions: The handle-or-declare rule the compiler checks, The throws clause on a method, RuntimeException and its subclasses are unchecked, Compiler error: unreported exception must be caught or declared
        • What to catch and what to leave alone: Why not to catch Error, such as OutOfMemoryError and StackOverflowError, Specific catch blocks before general ones, Multi-catch with a vertical bar, Compiler error: exception has already been caught, The danger of an empty catch block
        • The finally block and its traps: When finally runs and the System.exit exception to the rule, A return inside finally hides the real result, An exception thrown in finally replaces the original one, Order of try, catch and finally output
        • Chain exceptions with a cause: Constructors that take a cause, getCause and initCause, Finding the root cause with a loop, Losing the original error by not passing the cause
        • Read a stack trace with Caused by: Exception line, message and 'at' frames, Finding the first line from your own code, 'Caused by' sections and their order, What '... 5 more' means
        • Rethrow and wrap checked exceptions: Rethrowing the same exception after a log line, Precise rethrow with a final catch parameter, Wrapping in UncheckedIOException or a RuntimeException, Checked exceptions inside lambdas and streams
        • Why exceptions are not for normal flow: What creating an exception costs: the stack trace capture, Exceptions used as a goto: the anti-pattern, Check first versus try first, for example parsing numbers, Optional or a result value as the alternative
        • Exceptions in depth: common mistakes and practice: Output tracing with nested try, catch and finally, Fixing catch order and missing throws errors, Adding causes to wrapped exceptions, Interview: checked versus unchecked, throw versus throws
      • try-with-resources in Depth

        • Resources and why they must be closed: What a resource is: file handles, connections, locks, The operating system's limit on open files, Leaks and the 'too many open files' error, A locked file on Windows that cannot be deleted
        • Closing resources the old way: try and finally with close, The null check before close, Nested try blocks for two resources, Why this code is easy to get wrong
        • try-with-resources step by step: The resource declaration in brackets, AutoCloseable versus Closeable, close runs before catch and finally, Using an existing effectively final variable as the resource
        • Several resources and their close order: Declaring several resources with semicolons, Closing in reverse order, What happens when the second resource fails to open, Wrapped streams: which object to declare
        • Suppressed exceptions: An exception in the body and another in close, addSuppressed and getSuppressed, The 'Suppressed:' part of a stack trace, How old finally code lost the main exception
        • Write your own AutoCloseable class: Implementing close, Making close safe to call twice, Declaring a narrower exception on close, or none, Uses: timers, temporary folders, undo actions
        • Replace finally-close code with try-with-resources: Refactoring old close code step by step, When finally is still the right tool: unlock, reset state, Resources returned from methods: who closes them, Interview: finally versus try-with-resources
        • try-with-resources: common mistakes and practice: Close order tracing, Suppressed exception tracing, Fixing leaky code, Designing a closeable helper
      • Paths & Files

        • Path: naming a file in Java: Path.of and the older Paths.get, getFileName, getParent and getRoot, A Path is only a name: the file may not exist, The old java.io.File class and toPath
        • Relative and absolute paths: The working directory and user.dir, toAbsolutePath, Why a file is found in the terminal but not in the IDE, resolve, resolveSibling, normalize and relativize
        • Paths that work on Windows, macOS and Linux: Backslash versus forward slash and escaping in string literals, Case-sensitive names on Linux, case-insensitive on Windows, Reserved names and characters on Windows, such as CON and colon, user.home and building paths from parts, Hardcoded drive letters as a trap
        • Check, create and delete files and folders: exists, isRegularFile, isDirectory and isReadable, createFile, createDirectory and createDirectories, delete versus deleteIfExists, NoSuchFileException, FileAlreadyExistsException and DirectoryNotEmptyException
        • Copy and move files with options: Files.copy and Files.move, REPLACE_EXISTING, COPY_ATTRIBUTES and ATOMIC_MOVE, Renaming is a move, Moving across drives and partitions
        • File size, dates and temporary files: Files.size and getLastModifiedTime, Converting FileTime to java.time, createTempFile and createTempDirectory, Why deleteOnExit is not enough
        • List and walk folders: Files.list for one folder, Glob patterns with newDirectoryStream, Files.walk with a depth limit, Files.find with a condition, Closing these streams with try-with-resources
        • Copy or delete a whole folder tree safely: Deleting a tree: walk in reverse order, walkFileTree with SimpleFileVisitor, Symbolic links and loops, Path traversal: normalize and check startsWith a base folder, Confirming before deleting
        • Paths and files: common mistakes and practice: Fixing Windows-only path code, Folder size calculator, Find files by extension, Safe delete with checks
      • Reading & Writing Text Files

        • Read a small text file: Files.readString, Files.readAllLines, The whole file sits in memory, NoSuchFileException and its message
        • Write a text file: Files.writeString and Files.write with lines, Default options: create and truncate, Appending with StandardOpenOption.APPEND, CREATE_NEW to protect an existing file
        • Character sets and UTF-8: How characters become bytes, UTF-8 versus the old Windows default character set, Default charset rules: Java 17 versus Java 18 and later, MalformedInputException and garbled Hindi or rupee symbols, Always passing StandardCharsets.UTF_8
        • Line endings on Windows and Linux: CRLF versus LF, System.lineSeparator and %n, The hidden carriage return bug when splitting on \n, Which methods handle both endings
        • Large files with Files.lines: Why readAllLines fails on huge files: OutOfMemoryError, Files.lines reads lazily, Closing the stream with try-with-resources, filter, map and count on lines, UncheckedIOException inside the stream
        • BufferedReader and BufferedWriter: Files.newBufferedReader and newBufferedWriter with a charset, The readLine loop and null at the end, newLine, flush and close, Keeping a line number while reading
        • Scanner versus BufferedReader: Scanner on a Path with a charset, Token reading with nextInt and its traps, Speed difference on big input, Fast input reading for coding rounds
        • Write files safely: The half-written file after a crash, Write to a temporary file, then ATOMIC_MOVE, Keeping a backup copy, Disk full and permission errors while writing
        • Text files: common mistakes and practice: Word and line counter, Search a large log for a word, Fixing a charset bug, Merging two files
      • Byte & Character Streams

        • Bytes and characters: What a stream is, Byte data versus character data, The four base classes of java.io, Wrapping one stream in another
        • InputStream and OutputStream: read returns an int and -1 at the end, read into a byte array and its count, write and close, readAllBytes and transferTo
        • Copy binary files such as images: The buffer copy loop, Why a Reader corrupts an image, transferTo and Files.copy, Checking the copy by size
        • Buffering and why it matters: One system call per byte versus per block, BufferedInputStream and BufferedOutputStream, Measuring time with System.nanoTime, flush and what is lost without it
        • Reader and Writer for characters: FileReader and FileWriter and their charset trap, Charset constructors since Java 11, StringReader and StringWriter for testing, Reading into a char array
        • Bridge bytes to characters: InputStreamReader and OutputStreamWriter with a charset, Reading System.in as text, Reading a file from the classpath with getResourceAsStream, Stacking a BufferedReader on top
        • PrintWriter for formatted output: println and printf to a file, Auto flush, PrintWriter hides errors: checkError, System.out is a PrintStream
        • Simple binary formats with data streams: DataOutputStream writeInt, writeDouble and writeUTF, Reading back in the same order, EOFException at the end, Binary versus text formats: size and readability
        • Byte and character streams: common mistakes and practice: File checksum with a byte loop, Image copier with progress, Fixing a corrupted copy, Choosing the right stream chain
      • CSV & Structured Text

        • Turn a CSV line into a record: What a CSV file is, split, trim and parse numbers, A record class for each row, Skipping the header row
        • Read a whole CSV file into objects: Files.lines with skip and map, Empty and blank lines, Keeping line numbers with a loop, Collecting into a list or map
        • Quoted fields and commas inside values: Why split on comma breaks, Quoting rules and doubled quotes, A small character-by-character parser, Testing the parser with tricky lines
        • Skip and report bad rows: Validating each field, A RowError record with line number and reason, Continue or stop: an error limit, Writing an error report file
        • Write CSV output and text reports: Escaping commas and quotes when writing, Aligned text reports with String.format, Locale and decimal points in numbers, UTF-8 files that spreadsheets open correctly
        • Properties files for settings: The key=value format, Loading with a UTF-8 Reader, getProperty with a default, Settings order: file, system property, environment variable
        • Write simple JSON text by hand: The shape of JSON: objects, arrays, values, Building JSON with text blocks and StringBuilder, Escaping quotes, backslashes and new lines, Why real projects use a JSON library
        • CSV and structured text: common mistakes and practice: Marks file to grade report, Merge two CSV files by id, Fixing a broken parser, Settings loader with defaults
      • Serialization Basics

        • What serialization means: Objects to bytes and back, The Serializable marker interface, writeObject with ObjectOutputStream, readObject with ObjectInputStream and the cast
        • Object graphs and NotSerializableException: Nested objects and collections are saved too, NotSerializableException and its message, Shared references are written once, Inheritance and serializable parents
        • transient fields: Skipping passwords and caches, Default values after reading back, static fields are not saved, Rebuilding transient values
        • serialVersionUID and class changes: InvalidClassException after a change, The generated versus declared value, Compatible and incompatible changes, Declaring it explicitly
        • Records and validation while reading: Records are rebuilt through their constructor, Validation in a compact constructor still runs, readObject in a normal class for checks, Why plain classes can skip constructor checks
        • Why reading untrusted data is dangerous: Deserialization can run code: the gadget chain idea, Huge or deep data that stops a program, ObjectInputFilter to allow only known classes, The rule: never deserialize untrusted input
        • Text formats as the usual choice: Readable, editable and language-neutral data, CSV, JSON and properties compared, Where Java serialization still appears, Interview: Serializable versus a text format
        • Serialization: common mistakes and practice: Save and load a game score list, Fixing NotSerializableException, transient output tracing, Moving a saved list to CSV
      • Designing Error Handling

        • Checked or unchecked for your own exceptions: Recoverable problems the caller must handle, Programming bugs and broken rules, How modern Java code leans to unchecked, Interview: when would you make an exception checked
        • Design a good exception class: One base exception for an application, Extra fields: error code, line number, value, Constructors with message and cause, An enum of error codes
        • Validate early and fail fast: Objects.requireNonNull with a message, IllegalArgumentException and IllegalStateException, Guard clauses at the top of a method, Validation in record compact constructors
        • Translate exceptions at layer boundaries: Layers: storage, service and user interface, IOException becomes a StorageException, Keeping the cause, Not leaking file paths to the caller
        • Messages for users versus developers: What a good message says: what, which value, what to do, No stack traces on the user's screen, No passwords or personal data in messages, Exit codes for command-line programs
        • Log errors with java.util.logging: Logger.getLogger and levels, Logging an exception with log(Level.SEVERE, message, e), Writing logs to a file with FileHandler, logging.properties, Why printStackTrace is not logging
        • Where to catch: anti-patterns: Swallowed exceptions, Log and rethrow: the same error logged twice, catch Exception everywhere, One top-level handler in main, Uncaught exception handler for threads
        • Retry and recover from file errors: Temporary versus permanent errors, A retry loop with a limit and a wait, Fallback values such as default settings, AccessDeniedException from a file locked on Windows
        • Error handling interview review: Checked versus unchecked, finally versus try-with-resources, Suppressed exceptions, throw versus throws, final versus finally, Designing errors for a small app
        • Designing error handling: practice: Refactor a program that swallows errors, Add logging and user messages, Design exceptions for a booking app, Retry a file read
      • Files & I/O Mini Projects

        • CSV expense tracker: Expense record with date, category and amount, Add, list and total from a menu, Save and load with UTF-8 CSV, Safe writes and a monthly report
        • Log file analyzer: Read a large log with Files.lines, Parse level, time and message, Count errors per hour and top messages, Write a summary report
        • Folder organiser: Walk a folder and group files by extension, Move files into type folders, Name clashes and a dry-run mode, An undo log
        • Student records import with error report: Parse a CSV with quoted fields, Validate each row into a record, Collect errors with line numbers, Write valid rows and an error report
        • Settings-driven backup tool: Read source and target folders from a properties file, Copy only changed files by size and modified time, Log each step with java.util.logging, Retry locked files and print a final summary
    3. Multithreading & Concurrency

      Threads, synchronisation, executors, concurrent collections and CompletableFuture, with the classic concurrency bugs and their fixes.

      • Thread Basics

        • What is a thread?: Program, process and thread in plain words, A canteen with one counter versus many counters, Concurrency versus parallelism, and CPU cores, The main thread every program starts with
        • Create a thread with Thread and Runnable: Extending Thread and overriding run(), Implementing Runnable and passing it to Thread, Runnable as a lambda, Naming threads and Thread.currentThread().getName()
        • start() versus run(): run() runs on the calling thread, start() creates a new call stack, Calling start() twice and IllegalThreadStateException, Proving it with thread names in the output
        • Why thread output changes every run: The thread scheduler decides who runs, Interleaving of print statements, Reading "one possible output" in examples, Listing which outputs are possible and which are not
        • Pause and wait: sleep and join: Thread.sleep and the checked InterruptedException, join() to wait for a thread to finish, join with a timeout, Reading results only after join
        • Stop a thread politely with interrupt: The interrupt flag and isInterrupted(), InterruptedException clears the flag, Restoring the interrupt in a catch block, Why Thread.stop() is deprecated
        • Thread states and daemon threads: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED, Checking a state with getState(), Daemon threads and when the JVM exits, Priorities are only hints
        • What happens when a thread throws: An exception ends only that thread, Why main cannot catch another thread's exception, UncaughtExceptionHandler, Logging failures from worker threads
        • Thread basics: common mistakes and practice: Calling run() instead of start(), Forgetting join before reading a result, Swallowing InterruptedException, Mixed exercises on creating and controlling threads
      • Race Conditions & synchronized

        • Two threads, one variable: Heap objects are shared, local variables are not, Two threads updating one counter, A railway reservation counter as an analogy, What a race condition is
        • Why count++ is not safe: count++ is read, add, write, A step-by-step timeline of a lost update, Why the final count changes from run to run, Why a test that passes once proves nothing
        • Check-then-act bugs: The last train seat booked twice, containsKey followed by put on a shared map, Lazy initialisation that creates two objects, Compound actions must be atomic
        • synchronized methods: Every object has a built-in lock (monitor), One thread at a time inside a synchronized method, Fixing the shared counter, Static synchronized methods lock the class
        • synchronized blocks and which object is the lock: synchronized (this) versus a private final lock object, Two threads locking different objects protect nothing, Never lock on String literals or boxed Integers, Reentrancy: a thread can take a lock it already holds
        • Keep locked sections small: Why slow work inside a lock makes everyone wait, Moving printing, files and network calls outside the lock, Copy under the lock, use outside, Too small: splitting one atomic action across two locks
        • Design a thread-safe class: Invariants and the lock that guards them, Reads need the lock too, Encapsulation: never leak the mutable state, A thread-safe bank account step by step
        • Race conditions: common mistakes and practice: Unsynchronized reads, Locking on the wrong object, Check-then-act in booking code, Mixed fix-the-race exercises
      • Visibility & volatile

        • When a thread cannot see a change: A stop flag loop that may never end, CPU caches and compiler reordering as a simple picture, Why the bug may or may not show on your machine, Visibility versus atomicity
        • volatile and what it does not fix: volatile reads and writes go to main memory, Fixing the stop flag, volatile count++ is still a race, When volatile is the right tool
        • Happens-before in plain words: Program order inside one thread, Unlock before a later lock of the same monitor, volatile write before a later read, Thread start() and join() rules
        • Safe publication and the singleton trap: Seeing a half-built object, final fields and the guarantee they give, Double-checked locking and why it needs volatile, The holder class idiom and enum singletons
        • Share immutable objects safely: Why immutable objects need no locks, Records and final fields as shared data, Replace the whole object behind a volatile reference, List.copyOf and unmodifiable views
        • ThreadLocal for per-thread data: SimpleDateFormat is not thread-safe, ThreadLocal.withInitial, Calling remove() when threads are reused, DateTimeFormatter as the simpler fix
        • Visibility: common mistakes and practice: Missing volatile on a flag, volatile used where a lock is needed, Unsafe lazy initialisation, Mixed review exercises
      • Thread Coordination

        • Why threads need to wait for each other: Busy waiting wastes the CPU, A canteen token counter as an analogy, Waiting for a condition to become true, The guarded block pattern
        • wait and notify: wait() must be called while holding the lock, IllegalMonitorStateException, wait() releases the lock, sleep() does not, Always wait inside a while loop
        • notify versus notifyAll: notify wakes one waiting thread, notifyAll wakes all, The wrong thread woken and a program that hangs, Missed signals, Spurious wakeups
        • Producer-consumer with wait and notify: The bounded buffer problem, Waiting while full and while empty, Two producers and two consumers, Tracing the buffer step by step
        • BlockingQueue: the simpler way: put() and take() block for you, offer() and poll() with a timeout, Rewriting the bounded buffer with ArrayBlockingQueue, Why ready-made tools beat hand-written wait/notify
        • Stop worker threads cleanly: A volatile running flag versus interrupt, The poison pill message, Draining remaining work before exit, Shutting down producers before consumers
        • Thread coordination: common mistakes and practice: if instead of while around wait, Calling notify without the lock, Workers that never stop, Mixed producer-consumer exercises
      • Locks & Atomic Variables

        • ReentrantLock and unlock in finally: The Lock interface, lock() and unlock(), Why unlock() always goes in finally, What happens when unlock is forgotten
        • tryLock, timeouts and fair locks: tryLock() without waiting, tryLock with a timeout, lockInterruptibly(), Fair versus unfair locks
        • Condition objects: waiting with a Lock: newCondition(), await() and signal(), Separate notFull and notEmpty conditions, Bounded buffer rewritten with a Lock, Comparison with wait and notify
        • synchronized versus ReentrantLock: Feature comparison: tryLock, timeouts, fairness, conditions, Automatic release versus manual unlock, Which one to choose by default, The common interview answer
        • ReadWriteLock for read-heavy data: Many readers or one writer, ReentrantReadWriteLock for a settings cache, A read lock cannot be upgraded to a write lock, When a plain lock is faster
        • AtomicInteger and AtomicLong: incrementAndGet versus getAndIncrement, updateAndGet and accumulateAndGet with lambdas, AtomicReference and AtomicBoolean, volatile versus atomic variables
        • Compare-and-set: how atomics work: compareAndSet(expected, newValue), The retry loop, Lock-free does not mean wait-free, The ABA problem in simple words
        • LongAdder for busy counters: Why many threads slow down one AtomicLong, LongAdder keeps several cells and adds them up, sum() is not an exact snapshot, When AtomicLong is still the right choice
        • Locks and atomics: common mistakes and practice: unlock outside finally, Two atomics updated separately, Choosing lock, atomic or LongAdder, Mixed exercises
      • Executors & Thread Pools

        • Why use a thread pool?: The cost of creating a thread for every task, A canteen with fixed staff and a queue of orders, Task versus thread, Executors.newFixedThreadPool
        • ExecutorService: submit and execute: execute() versus submit(), Fixed, single and cached pools, Pool thread names in the output, Exceptions hidden inside submit()
        • Callable and Future: Callable returns a value and may throw, Future.get() blocks, get with a timeout, ExecutionException and the real cause, cancel() and isDone(), Runnable versus Callable
        • invokeAll and invokeAny: Running a list of Callables with invokeAll, Collecting results in order, invokeAny for the first successful answer, Timeouts on both
        • Run tasks later and repeatedly: ScheduledExecutorService.schedule, scheduleAtFixedRate versus scheduleWithFixedDelay, An exception silently stops a repeating task, A reminder or heartbeat example
        • Shut down a pool correctly: Why the program does not exit, shutdown(), awaitTermination() and shutdownNow(), The standard shutdown pattern, ExecutorService with try-with-resources (Java 21)
        • Choose a pool size and configure ThreadPoolExecutor: CPU-bound work: about one thread per core, I/O-bound work: more threads, based on wait time, Core size, max size, queue and rejection policy, The danger of unbounded queues and cached pools
        • Virtual threads (Java 21): Platform threads versus virtual threads, Thread.ofVirtual() and newVirtualThreadPerTaskExecutor(), When they help (blocking I/O) and when they do not (CPU work), Pinning, and structured concurrency as a preview feature
        • Executors: common mistakes and practice: Forgetting shutdown, Calling get() too early, Wrong pool type for the job, Mixed exercises with pools and futures
      • Concurrent Collections

        • Normal collections under many threads: ArrayList losing items or throwing, HashMap corrupted by concurrent puts, ConcurrentModificationException, Vector and Hashtable as legacy options
        • Collections.synchronizedList and its limits: synchronizedList and synchronizedMap, Compound actions are still not atomic, Iteration must be locked by hand, One lock for everything slows threads down
        • ConcurrentHashMap basics: put and get from many threads, No null keys or values, and why, Weakly consistent iteration, size() is only an estimate under change
        • ConcurrentHashMap atomic methods: putIfAbsent and computeIfAbsent, merge for counting words, compute and computeIfPresent, Why get-then-put is still a race
        • How ConcurrentHashMap works inside: Buckets and why one big lock is slow, Java 7 segments versus locking one bucket at a time, Reads without locks, empty buckets filled with compare-and-set, Resizing and tree bins in simple terms
        • CopyOnWriteArrayList: Every write copies the array, Snapshot iterators never throw ConcurrentModificationException, Listener lists as the ideal use, Why it is bad for frequent writes
        • Blocking queues compared: ArrayBlockingQueue versus LinkedBlockingQueue, Bounded versus unbounded queues, PriorityBlockingQueue and DelayQueue in brief, ConcurrentLinkedQueue for non-blocking use
        • Concurrent collections: common mistakes and practice: Wrapper iteration without a lock, get-then-put races, Choosing the right collection, Mixed exercises
      • Synchronizers

      • CompletableFuture

        • Why CompletableFuture?: Future.get() blocks the caller, Saying what to do when the result arrives, A food order token as an analogy, Pipelines of steps, like streams
        • supplyAsync and runAsync: Starting work in the background, The common ForkJoinPool, join() versus get(), Why main may exit before the work prints
        • thenApply, thenAccept and thenRun: Transforming a result with thenApply, Consuming a result with thenAccept, Running a step with thenRun, Which thread runs each step
        • thenCompose versus thenApply: Nested CompletableFuture<CompletableFuture<T>>, thenCompose flattens like flatMap, Dependent calls: find user, then fetch orders, Reading long chains
        • Combine tasks: thenCombine, allOf and anyOf: thenCombine for two independent results, allOf and collecting a list of results, anyOf for the fastest answer, Total time of parallel versus sequential calls
        • Handle errors: exceptionally, handle and whenComplete: How an exception skips later steps, exceptionally for a fallback value, handle for result or error, whenComplete and CompletionException wrapping
        • Your own executor and timeouts: Why blocking I/O should not use the common pool, Passing an executor to supplyAsync and the Async methods, orTimeout and completeOnTimeout, Shutting down the executor afterwards
        • CompletableFuture: common mistakes and practice: Calling join() too early, Lost exceptions at the end of a chain, thenApply where thenCompose is needed, Mixed pipeline exercises
      • Classic Concurrency Bugs

        • What is a deadlock?: Two bank transfers locking accounts in opposite order, A program that hangs without an error, The four conditions for deadlock, Why it appears only sometimes
        • Fix deadlocks with lock ordering: Always lock in a fixed order, such as by account id, tryLock with a timeout and back off, Using one lock instead of two, Avoid calling unknown code while holding a lock
        • Livelock and starvation: Two people stepping aside in a corridor, Retry with a random wait to break a livelock, Starvation from unfair locks and long holders, Comparing deadlock, livelock and starvation
        • Lost updates and broken invariants: Two fields that must change together, A min-max range that becomes invalid, Total money changing during transfers, Guarding a whole invariant with one lock
        • Read a thread dump: Taking a dump with jstack or jcmd Thread.print, Thread states and stack traces in the dump, "Found one Java-level deadlock", Naming threads to make dumps readable
        • Test concurrent code honestly: Why one passing run proves nothing, Running many times with a start latch, Checking invariants instead of exact output order, Timeouts so a deadlocked test fails instead of hanging
        • Concurrency interview review: synchronized versus ReentrantLock, volatile versus atomic, Runnable versus Callable, sleep versus wait, Deadlock conditions and thread pool sizing, ConcurrentHashMap internals in simple terms
        • Concurrency bugs: common mistakes and practice: Find the deadlock, Find the broken invariant, Read a short thread dump, Mixed fix-the-bug exercises
      • Concurrency Mini Projects

        • Parallel word counter: One Callable per file on a fixed pool, Merging counts with ConcurrentHashMap.merge, Top words sorted with streams, Comparing time against a single-threaded version
        • Bank transfers without deadlock: Account class with its own lock, Transfers that lock in account id order, Many threads making random transfers, Checking that the total balance never changes
        • Order processing with producers and consumers: Order producers feeding a bounded BlockingQueue, Worker pool that packs and bills orders, Poison pill shutdown without losing orders, Counting processed orders with an atomic counter
        • Price fetcher with CompletableFuture: Simulated shops with random delays, Fetching all prices in parallel with allOf, Timeouts and fallback prices, Picking the best offer on a custom executor
        • Railway ticket booking with many counters: Seats shared by many booking counter threads, No double booking with locks or atomic methods, A Semaphore to limit active counters, A CountDownLatch to open booking for everyone at once
    4. JVM Internals & Memory Management

      How the JVM loads and runs your code, how memory is organised, how garbage collection works and how to find memory problems.

      • From Source to Bytecode

        • From .java file to running program: javac turns source into bytecode, java starts the JVM, A simplified JVM model: class loader, memory areas, execution engine, garbage collector, Why bytecode makes Java portable, JDK, JRE and JVM: a quick refresher
        • What is inside a .class file: One .class file per class, including nested classes (Outer$Inner.class), Magic number CAFEBABE and the class file version (major 61 = Java 17), The constant pool, fields, methods and attributes, UnsupportedClassVersionError when the JVM is older than the compiler
        • Read bytecode with javap: javap -c to see method bytecode, javap -p for private members and javap -v for the constant pool, Method descriptors such as (I)V and (Ljava/lang/String;)I, javap -l for line numbers and local variable tables
        • How bytecode works: the operand stack: Each method has a local variable array and an operand stack, Load, store and arithmetic instructions: iload, istore, iadd, ireturn, Tracing a + b * c step by step, Branches and loops: if_icmpge and goto
        • What javac does with everyday Java code: Method calls: invokestatic, invokevirtual, invokeinterface, invokespecial, Autoboxing becomes Integer.valueOf and unboxing becomes intValue, String concatenation with invokedynamic (Java 9 and later), Enhanced for loops and lambdas in bytecode
        • How the JDK tools fit together: Build and run: javac, java, jar, jshell, Inspect: javap, Watch a running JVM: jps, jcmd, jstat, Java Flight Recorder, Where each tool is used in the rest of this section
        • Bytecode practice: compile, inspect and trace: Compile small programs and inspect them with javap, Trace operand stack contents for arithmetic and loops, Spot boxing and string concatenation in bytecode, Explain class file version errors
      • Class Loading

        • What class loading means: Classes are loaded lazily, the first time they are needed, Watching loads with -verbose:class or -Xlog:class+load, The Class object that represents a loaded class, A class is identified by its name and its class loader
        • Loading, linking and initialization: Loading: reading the bytes and creating the Class object, Linking: verification, preparation and resolution, Preparation sets static fields to default values, Initialization runs static initializers and static field assignments, VerifyError and what verification protects against
        • The bootstrap, platform and application class loaders: Bootstrap loader for core classes such as java.lang.String, Platform loader (Java 9 and later, replaces the extension loader), Application loader for your class path and module path, getClassLoader() and why it returns null for core classes
        • Parent delegation: A loader asks its parent first before loading a class itself, Why delegation keeps core classes safe and unique, loadClass versus findClass, What happens when the same class is on the class path twice
        • When a class is initialized: Triggers: new, static method call, non-constant static field, Class.forName, reflection, Superclass initialized before subclass, interfaces only when needed, Non-triggers: compile-time constants, array creation, .class literals, Static initialization order and ExceptionInInitializerError
        • ClassNotFoundException versus NoClassDefFoundError: ClassNotFoundException: a checked exception from Class.forName or loadClass, NoClassDefFoundError: the class existed at compile time but is missing at run time, NoClassDefFoundError: Could not initialize class, after a failed static initializer, Fixing the class path for java -cp and executable JARs
        • Custom class loaders and class identity: Loading classes from a folder or JAR with URLClassLoader, Same class name, two loaders: two different classes, ClassCastException between classes from different loaders, Where custom loaders are used: plugins, servers and reloading
        • Class loading practice: Predict static block output and initialization order, Diagnose class path errors from stack traces, Use -verbose:class to answer what was loaded and when, Explain loader hierarchy questions
      • Execution Engine & JIT

        • The interpreter and the JIT compiler: The interpreter runs bytecode one instruction at a time, The just-in-time (JIT) compiler turns hot code into machine code, The code cache where compiled code lives, HotSpot: the JVM in standard JDK builds
        • Hot methods and tiered compilation: Invocation and loop counters decide what is hot, C1 (fast compile) and C2 (strong optimization), Tiered compilation levels in simplified form, Watching compilation with -XX:+PrintCompilation, On-stack replacement for long-running loops
        • Method inlining: Inlining copies a small method's body into its caller, Why small getters and helper methods cost nothing after JIT, Call sites with one, two or many receiver types, simplified, Write clean code first: the JIT rewards small methods
        • Escape analysis in simple terms: An object escapes when it leaves the method or thread, Scalar replacement: fields kept in registers instead of the heap, Removing locks on objects no other thread can see, Why escape analysis is an optimization, not a guarantee
        • Deoptimization: when the JIT changes its mind: The JIT makes guesses from what it has seen so far, Loading a new subclass can break a guess, Going back to the interpreter and recompiling, made not entrant in compilation output
        • JIT warm-up and honest timing tests: Warm-up: why the first runs are slow, Why one System.nanoTime measurement misleads, Dead code removal and GC noise in timing tests, JMH, the OpenJDK benchmark harness, at a glance, Startup help: class data sharing (on by default since Java 12)
        • Execution engine practice: Watch methods become hot with -XX:+PrintCompilation, Compare first-run and warmed-up timings, Find the flaw in broken micro-benchmarks, Interview questions on interpreter, JIT and warm-up
      • JVM Memory Areas

        • The JVM memory map: Shared areas: heap and method area (metaspace in HotSpot), Per-thread areas: JVM stack, program counter, native method stack, Memory outside the heap: code cache, thread stacks, direct buffers, A simplified diagram you will reuse all section
        • Stack frames and local variables: A new frame for every method call, removed when it returns, Local variable array, operand stack and return address, Primitives store values, references store a way to reach the object, Tracing frames during nested calls and recursion
        • Heap versus stack: Objects and arrays live on the heap, references live in frames, Lifetime: frames end with the call, objects live while reachable, Speed and size differences, Tracing a full program with a memory diagram, Interview answer: heap versus stack in four sentences
        • Each thread's own stack: Every platform thread gets its own stack, Stack size and the -Xss option, Why local variables are thread-safe and heap objects are shared, Memory cost of many threads, Java 21: virtual threads keep their stacks on the heap
        • Metaspace, static fields and the String pool: Metaspace holds class metadata in native memory (Java 8 and later, replaced PermGen), Static field values are stored with the Class object on the heap (HotSpot, Java 8 and later), The String pool is on the heap (since Java 7), -XX:MaxMetaspaceSize and too many loaded classes
        • StackOverflowError and OutOfMemoryError: which area ran out: StackOverflowError: one thread's stack is full, OutOfMemoryError: Java heap space and GC overhead limit exceeded, OutOfMemoryError: Metaspace and unable to create native thread, Errors versus exceptions: why you rarely catch these
        • Memory areas review: trace a whole program: Trace frames, heap objects and static fields for one program, Common mistakes: objects on the stack, strings copied on assignment, Mixed questions across the module, Interview drill on memory areas
        • Memory areas practice: Draw memory diagrams for given programs, Trigger and explain StackOverflowError with a small -Xss, Trigger heap OutOfMemoryError with a small -Xmx, Predict outputs that depend on shared references
      • Objects in Memory

        • What an object looks like in memory: The object header: mark word and class pointer, Fields and alignment padding to 8 bytes, Compressed references on 64-bit HotSpot with heaps under 32 GB, Typical sizes, labelled as approximate: new Object() takes about 16 bytes
        • Estimating and measuring object size: Adding up header, fields and padding by hand, Shallow size versus the size of everything an object holds, Seeing real layouts with JOL (Java Object Layout, an OpenJDK tool), Rough measurement with Runtime.totalMemory and freeMemory
        • Arrays in memory: int[] versus Integer[]: Array header with a length field, int[] stores values side by side, Integer[] stores references to separate objects, 2D arrays are arrays of arrays
        • The Integer cache and == surprises: Integer.valueOf caches -128 to 127, Why == works for 100 and fails for 1000, Caches in Byte, Short, Long, Character and Boolean, Always compare wrappers with equals
        • Strings in memory and interning: Literals go to the String pool; new String makes a new object, intern() and when it helps, Compact strings: byte[] with LATIN1 or UTF16 (Java 9 and later), substring copies characters (since Java 7u6), G1 string deduplication with -XX:+UseStringDeduplication
        • Why boxing in big collections costs memory: List<Integer> versus int[] for a million values, Per-entry cost of HashMap: entry, key and value objects, Primitive-friendly options: arrays, BitSet, IntStream, Designing memory-friendly classes
        • Objects in memory practice: Estimate sizes of classes and arrays, Fix == comparisons on wrappers and strings, Rewrite a boxed collection with primitives, Interview questions on the String pool and Integer cache
      • Garbage Collection Basics

        • What garbage collection does: Automatic memory management: no free() in Java, What counts as garbage, System.gc() is only a request, finalize() is deprecated (Java 9) and marked for removal (Java 18)
        • Reachability and GC roots: GC roots: local variables in live frames, static fields, live threads, JNI references, The object graph and reachable objects, Cycles of objects are still collected, Why Java does not use reference counting, Interview answer: how GC decides what is garbage
        • Mark, sweep and compact: Mark: find all reachable objects, Sweep: reclaim the rest, Compact and copy: move live objects together, Fragmentation and fast bump-pointer allocation, Thread-local allocation buffers (TLABs)
        • Young and old generations: Most objects die young: the generational idea, Eden and the two survivor spaces, Object age, tenuring and promotion to the old generation, In G1 the generations are sets of regions, Humongous objects in G1
        • Minor, mixed and full collections: Young (minor) collections and why they are cheap, G1 mixed collections that also clean old regions, Full GC and why it is a warning sign, Premature promotion, Remembered sets in simple terms
        • Stop-the-world pauses: Why application threads must stop for some GC work, Safepoints in simple terms, Concurrent phases that run beside your code, Latency, throughput and memory footprint: the three trade-offs
        • Garbage collection review: trace the garbage: Mark which objects become garbage line by line, Common wrong ideas: setting to null everywhere, calling System.gc(), Mixed questions across the module, Interview drill on GC basics
        • Garbage collection practice: Count eligible objects after each line, Explain reachability through static fields and collections, Watch young and full collections with -Xlog:gc, Interview questions on generations and pauses
      • Garbage Collectors & JVM Options

        • Serial, Parallel, G1 and ZGC at a glance: Serial and Parallel: simple and throughput-focused, G1: the default collector on most machines since Java 9, ZGC: very short pauses, production-ready since Java 15, Java 21: generational ZGC with -XX:+UseZGC -XX:+ZGenerational, Selecting one with -XX:+UseSerialGC, -XX:+UseParallelGC, -XX:+UseG1GC, -XX:+UseZGC
        • How G1 works: The heap as equal-size regions, Pause time goal with -XX:MaxGCPauseMillis (default 200 ms), Young and mixed collections, Concurrent marking of the old generation, Collecting the regions with the most garbage first
        • Heap size and memory options: -Xms and -Xmx for starting and maximum heap, Default maximum heap: about a quarter of physical memory, -XX:MaxRAMPercentage for containers, -Xss and -XX:MaxMetaspaceSize, Checking real values with -XX:+PrintFlagsFinal and jcmd VM.flags
        • Turning on GC logs: Unified logging (Java 9 and later): -Xlog:gc, More detail with -Xlog:gc*, Writing to a file: -Xlog:gc*:file=gc.log, Java 8 used -XX:+PrintGCDetails (replaced by -Xlog in Java 9)
        • Reading a GC log: Reading one line: pause type, cause, heap before and after, time, Pause Young (Normal), Pause Young (Mixed) and Pause Full, Signs of trouble: rising heap after GC, frequent full GCs, long pauses, Comparing a healthy log with a leaking one
        • When to change settings and when to fix the code: Measure first, change one thing at a time, More heap hides a leak but does not fix it, Reduce allocation: boxing, temporary objects, big copies, A short list of options worth knowing for a first job
        • Garbage collectors and options practice: Run one program with different collectors and compare logs, Set heap limits and observe the effect, Read sample GC logs and name the problem, Interview questions on collectors and options
      • References & Memory Leaks

        • What a memory leak means in Java: Objects you no longer need but still reach, Symptoms: heap after GC keeps growing, then OutOfMemoryError, A leak versus a program that simply needs more memory, Interview answer: can Java leak memory?
        • Strong, soft, weak and phantom references: Strong references: the normal kind, SoftReference: cleared when memory runs low, WeakReference: cleared at the next GC once nothing strong remains, PhantomReference and ReferenceQueue, Checking get() for null
        • WeakHashMap and safe caches: WeakHashMap removes entries when keys become unreachable, Traps: literal String keys, values that point to their keys, Why soft-reference caches behave badly under load, A bounded LRU cache with LinkedHashMap and removeEldestEntry
        • Cleaner and cleaning up resources: Why finalize() was a bad idea, java.lang.ref.Cleaner (Java 9 and later), try-with-resources comes first, A Cleaner as a safety net only
        • Leaks from static collections and caches: Static lists and maps live as long as the class, Unbounded caches keyed by user or session, Mutable keys in a HashMap that can never be removed, Fixes: limits, eviction and removing entries
        • Leaks from listeners, resources and ThreadLocal: Listeners and callbacks that are never removed, Unclosed streams, connections and readers, ThreadLocal values in thread pools and why remove() matters, Executor threads that are never shut down
        • Inner classes that hold the outer object: A non-static inner class keeps a hidden reference to Outer.this, Anonymous classes do the same, Lambdas capture this only when they use instance members, Fix: static nested classes
        • Memory leaks practice: Spot the leak in short programs, Fix caches, listeners and ThreadLocal misuse, Predict WeakReference and WeakHashMap behaviour, Interview questions on memory leaks in Java
      • Diagnosing Memory Problems

        • Find and inspect a JVM with jps and jcmd: jps -l to list running JVMs, jcmd <pid> help to see available commands, VM.version, VM.flags, VM.system_properties, GC.heap_info and GC.class_histogram
        • Watch the heap with jstat: jstat -gc <pid> 1000 for live numbers, jstat -gcutil: percentages for eden, survivors, old and metaspace, YGC, FGC and GC time columns, Spotting an old generation that never shrinks
        • Taking a heap dump: jcmd <pid> GC.heap_dump with a file name, -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath, jmap -dump:live,format=b,file=heap.hprof <pid>, Heap dumps can hold passwords and personal data: handle with care
        • Reading a heap dump: Class histogram: what takes the most space, Shallow size versus retained size, Dominators and the biggest retained objects, Path to GC roots: who is holding this object, Comparing two dumps taken some time apart
        • Reading a thread dump: jcmd <pid> Thread.print and jstack, Thread states and stack traces, Finding deadlocks and very deep stacks, Too many threads and unable to create native thread
        • VisualVM and JDK Mission Control: VisualVM: monitor, sampler and heap dump viewer, Java Flight Recorder: low-overhead recording built into the JDK (free in OpenJDK 11 and later), Starting a recording with jcmd JFR.start or -XX:StartFlightRecording, Opening a recording in JDK Mission Control
        • Reading an OutOfMemoryError message: Java heap space, GC overhead limit exceeded, Metaspace, unable to create native thread, Direct buffer memory, Requested array size exceeds VM limit, Why the stack trace shows who allocated last, not who leaked, -XX:+ExitOnOutOfMemoryError for services that should restart
        • A step-by-step diagnosis workflow: Observe: symptoms, logs and error messages, Measure: GC logs, jstat and jcmd, Capture: heap dumps, thread dumps and recordings, Fix one cause and verify with the same measurements
        • Diagnosing memory problems practice: Match tool output to the right problem, Read class histograms and GC logs, Answer what to run next in short scenarios, Interview questions on heap dumps and JDK tools
      • JVM Practice & Case Studies

        • Case study: fix a program that runs out of heap: A report program that loads a whole file into a list, Reproduce with a small -Xmx and a heap dump on error, Read the histogram and find the big collection, Rewrite to process line by line and verify
        • Case study: fix a deep-recursion StackOverflowError: Reading a stack trace with repeating frames, Missing base case versus input that is truly deep, Rewrite recursion with an explicit Deque, Why raising -Xss is only a stopgap
        • Case study: find a leak from a growing cache: A service whose memory grows every hour, Confirm with jstat and the GC log, Compare two heap dumps and follow the path to GC roots, Fix with a bounded cache and verify
        • Case study: explain a class loading error: A program that runs in the IDE but fails from a JAR, NoClassDefFoundError from a missing dependency on the class path, NoClassDefFoundError: Could not initialize class from a failing static block, Using jar tf, -verbose:class and the manifest to find the cause
        • Case study: investigate long GC pauses: A program with slow responses and busy GC logs, Read pause times and allocation rate from the log, Find heavy allocation with a flight recording, Cut boxing and temporary objects, then compare logs
  4. Stage 4: Build Applications

    Become a Java backend developer

    • SQL & Database Design
    • JDBC & Database Connectivity
    • Web Fundamentals, HTTP & REST APIs
    • Spring Framework & Spring Boot
    • Spring Data JPA & Hibernate
    • Spring Security & Authentication
    See this stage
    See all topics in Build Applications
    1. SQL & Database Design

      Design tables in MySQL, write SQL from simple queries to joins, window functions and reports, and understand indexes and transactions, then see the same ideas in PostgreSQL.

      • Databases & MySQL Setup

        • Why applications use a database: Storing data in files and where it breaks, What a database management system (DBMS) does for you, Many users at once, crash safety and fast search, Where the database sits in apps like IRCTC, Swiggy and a college ERP
        • Tables, rows and columns: A relational database is a set of tables, Rows are records, columns are fields, Every column has a name and a type, Keys that link one table to another, first look
        • SQL, and why we start with MySQL: SQL: one language to define, change and read data, The parts of SQL: DDL, DML, queries, transactions and permissions, MySQL, PostgreSQL, Oracle and SQL Server compared, Why MySQL first: beginner friendly and very common in Indian companies and college labs
        • Install MySQL Server and MySQL Workbench: Download MySQL 8.4 LTS for Windows or macOS, The root password and port 3306, Add the mysql client to your PATH, Check the install with mysql --version and Workbench
        • Run your first SQL in the mysql client: Connect with mysql -u root -p and read the prompt, SELECT VERSION(), NOW() and simple expressions, Semicolons, case and multi-line statements, SHOW DATABASES, USE, SHOW TABLES, DESCRIBE and exit, The same in a MySQL Workbench query tab
        • Create a database and a user: CREATE DATABASE and USE, Character set utf8mb4 for Indian names and emoji, CREATE USER 'app'@'localhost' with a password, GRANT: give a user access to one database
        • Load the practice databases: ShopLite: the online store this course builds, The practice data: store, employees, students and railway tables, Run the setup script with SOURCE or Workbench, Reset the practice data at any time
        • Practice: databases and setup: Mixed exercises on client commands, Create, switch and inspect databases, Read table structures with DESCRIBE and SHOW CREATE TABLE, Quick review of DBMS ideas
      • Creating Tables & Data Types

        • CREATE TABLE and DROP TABLE: CREATE TABLE with columns and types, See a table with DESCRIBE and SHOW CREATE TABLE, DROP TABLE and DROP TABLE IF EXISTS, Errors: table already exists, unknown table
        • Number types and DECIMAL for money: TINYINT, INT and BIGINT and their ranges, UNSIGNED numbers, DECIMAL(p, s): exact values for prices and fees, FLOAT and DOUBLE and their rounding errors, Out of range errors in strict mode
        • Text types: VARCHAR, TEXT, CHAR and ENUM: VARCHAR(n) and the length limit, TEXT for long text, CHAR(n) for fixed codes such as IFSC parts or PIN codes, ENUM for a fixed list, and its limits, The data too long error
        • Dates, times and booleans: DATE, TIME and DATETIME, TIMESTAMP and time zones, BOOLEAN is TINYINT(1) in MySQL, CURDATE(), NOW() and the 'YYYY-MM-DD' format
        • Auto-generated ids with AUTO_INCREMENT: AUTO_INCREMENT primary keys, LAST_INSERT_ID() after an insert, Ids are never reused and may have gaps, Starting value and resetting in practice tables
        • Change a table with ALTER TABLE: ADD COLUMN with and without a default, RENAME COLUMN and RENAME TABLE, MODIFY and CHANGE COLUMN, DROP COLUMN and what happens to the data
        • Naming, storage engines and character sets: snake_case names and singular or plural tables, Reserved words such as order and user, and backticks, InnoDB: the storage engine you should use, utf8mb4 and collations: why "Ravi" equals "ravi"
        • Practice: tables and data types: Choose types for real requirements, Fix wrong types, Change tables with ALTER TABLE, Mixed review
        • Mini project: college library tables: Read the requirement for a college library, Create tables for books, members and loans, Choose types and AUTO_INCREMENT ids, Insert sample rows and check them
      • Keys & Constraints

        • Primary keys: What a primary key guarantees, Natural keys versus surrogate keys, Composite primary keys, Duplicate entry errors
        • NOT NULL and DEFAULT: NOT NULL: a value is required, DEFAULT values and DEFAULT in INSERT, Strict mode and what happens without it, The cannot be null error
        • UNIQUE and CHECK constraints: UNIQUE on one and on several columns, UNIQUE and NULL, CHECK rules such as price > 0 (MySQL 8.0.16 and later), Naming constraints so errors are readable
        • Foreign keys: linking two tables: A foreign key points to a primary key, REFERENCES in CREATE TABLE and ALTER TABLE, What the database refuses: missing parents, Insert order: parents before children
        • ON DELETE: CASCADE, RESTRICT and SET NULL: What happens to children when a parent is deleted, RESTRICT and NO ACTION, CASCADE and its risks, SET NULL, Choosing the rule for orders and customers
        • Practice: keys and constraints: Add the right constraints to a table, Predict which inserts fail, Fix tables that accept bad data, Mixed review
        • Mini project: hostel room allocation: Requirement: hostels, rooms, students and allocations, Primary and foreign keys, CHECK rules for room capacity and dates, Prove the constraints reject bad data
      • Inserting, Updating & Deleting Data

        • INSERT one row and many rows: INSERT INTO ... VALUES, Naming the columns and why, Several rows in one INSERT, INSERT ... SELECT
        • UPDATE with a WHERE clause: UPDATE ... SET ... WHERE, Updating several columns and using expressions, UPDATE without WHERE, and safe update mode in Workbench, Check first with SELECT, then update
        • DELETE and TRUNCATE: DELETE ... WHERE, DELETE without WHERE, TRUNCATE and how it differs, Deleting rows that other tables reference
        • Generated ids and affected rows: LAST_INSERT_ID() after one and many rows, ROW_COUNT(): how many rows changed, Why applications need the new id, Reading the Query OK and Rows matched messages
        • Upserts with ON DUPLICATE KEY UPDATE: The insert-or-update problem, INSERT ... ON DUPLICATE KEY UPDATE, INSERT IGNORE and its risks, REPLACE and why it deletes first
        • Practice: changing data: Insert, update and delete tasks, Predict how many rows change, Fix dangerous statements, Mixed review
        • Mini project: student marks register: Tables for students, subjects and marks, Insert a semester of marks, Correct marks and remove withdrawn students, Upsert re-evaluation results
      • Querying Data

        • SELECT columns and aliases: SELECT * and naming columns, Expressions in SELECT, Column aliases with AS, Why SELECT * is avoided in applications
        • Filter rows with WHERE: Comparison operators, AND, OR and NOT, Brackets and operator precedence, Comparing text and dates
        • IN, BETWEEN, LIKE and REGEXP: IN with a list, BETWEEN and its inclusive ends, LIKE with % and _, and case-insensitive matching, REGEXP for patterns such as valid PIN codes
        • NULL values and IS NULL: What NULL means, Why = NULL never matches, IS NULL and IS NOT NULL, IFNULL and COALESCE, Three-valued logic in WHERE
        • ORDER BY and LIMIT: Sorting ascending and descending, Sorting by several columns, Where NULLs go when sorting, LIMIT and OFFSET for top N and paging
        • DISTINCT and CASE expressions: DISTINCT on one and several columns, CASE WHEN for labels and buckets, CASE in ORDER BY, IF() as MySQL shorthand
        • String functions: UPPER, LOWER, LENGTH, CHAR_LENGTH and TRIM, CONCAT and CONCAT_WS, SUBSTRING, LOCATE and REPLACE, LPAD and formatting for reports
        • Number and date functions: ROUND, TRUNCATE, CEIL, FLOOR and DIV, CAST and implicit conversion surprises, DATE_FORMAT, YEAR, MONTH and DAYNAME, DATEDIFF, DATE_ADD and TIMESTAMPDIFF
        • Practice: single-table queries: Filter, sort and page results, Handle NULL in real data, Format results with functions, Mixed review
        • Mini project: IPL player statistics: A table of IPL batting records, Answer the questions a sports channel asks, Strike rate and average with functions, Deliver the answers as a reviewed SQL file
      • Aggregates & Grouping

        • COUNT, SUM, AVG, MIN and MAX: Aggregates turn many rows into one, COUNT(*) versus COUNT(column), How aggregates treat NULL, Rounding averages
        • GROUP BY one and several columns: One result row per group, Grouping by several columns, ONLY_FULL_GROUP_BY: every selected column grouped or aggregated, Grouping by an expression such as the month
        • HAVING versus WHERE: WHERE filters rows before grouping, HAVING filters groups after grouping, Using both in one query, COUNT(DISTINCT ...) and conditional counts with SUM(CASE ...)
        • The order a SELECT runs in: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, Why an alias cannot be used in WHERE, Where MySQL allows aliases and where it does not, Debugging a query step by step
        • Report queries: sales per month and top customers: Revenue per month, Top customers by spending, Subtotals and grand totals with WITH ROLLUP, Turning a business question into GROUP BY
        • Practice: aggregates and grouping: Group and filter real data, Predict results with NULLs, Fix GROUP BY mistakes, Mixed review
        • Mini project: ShopLite monthly sales report: The report the ShopLite owner asks for, Monthly revenue, order counts and average order value, Category and city breakdowns with subtotals, Present the numbers clearly
      • Joins

        • Why data is split across tables, and joins: One fact in one place, Keys connect the tables, A join pairs rows on a condition, Joining without a condition: every pair
        • INNER JOIN step by step: JOIN ... ON with matching keys, Table aliases, Choosing columns from both tables, Rows without a match disappear
        • LEFT and RIGHT JOIN: Keeping every row from the left table, NULLs where there is no match, RIGHT JOIN and why LEFT is preferred, Conditions in ON versus WHERE
        • FULL OUTER JOIN and CROSS JOIN: MySQL has no FULL OUTER JOIN: build it with UNION, UNION versus UNION ALL, CROSS JOIN: every combination, Spotting an accidental cross join
        • Self join: employees and managers: Joining a table to itself, Aliases make it readable, Employees with their managers, Pairs from the same table
        • Joining three or more tables: Customers, orders, order items and products, Following the keys one join at a time, Joins with GROUP BY, Duplicate rows from one-to-many joins
        • Finding missing data with LEFT JOIN ... IS NULL: The anti-join pattern, Customers who never ordered, Trains with no bookings, Comparing with NOT EXISTS
        • Practice: joins: Interview-style join questions, Predict row counts, Fix wrong joins, Mixed review
        • Mini project: railway reservation queries: Trains, stations, routes, passengers and bookings, Seat availability and waiting lists, Passenger journey reports across many tables, Trains and routes with no bookings
      • Subqueries, Views & Window Functions

      • Database Design & Normalisation

        • Entities, attributes and ER diagrams: From a requirement to entities, Attributes and identifiers, Drawing an ER diagram (Workbench and on paper), Reading an ER diagram
        • One-to-one and one-to-many relationships: Cardinality: how many on each side, One-to-many with a foreign key on the many side, One-to-one and where the key goes, Optional versus required relationships
        • Many-to-many with join tables: Why many-to-many needs a third table, The join table and its composite key, Extra columns on the relationship, Students and courses, orders and products
        • Anomalies and why we normalise: One wide spreadsheet-style table, Update, insert and delete anomalies, What normalisation means, Functional dependencies in plain words
        • First normal form (1NF): Atomic values: one value per cell, Repeating groups and comma-separated lists, Fixing a table that breaks 1NF, A worked example
        • Second and third normal form: Partial dependencies and 2NF, Transitive dependencies and 3NF, Worked example: an exam results sheet to 3NF, BCNF in one paragraph
        • When denormalising is reasonable: The cost of many joins, Storing totals and copies on purpose, Keeping copies correct, Reporting tables and views
        • Practice: database design: Design from short requirements, Find and fix normalisation problems, Choose relationships and keys, Mixed review
        • Mini project: courier delivery database: Requirement: restaurants, menus, customers, orders and delivery partners, ER diagram and normalised tables, CREATE script with keys and constraints, Sample data and five business queries
      • Indexes & Query Performance

        • Full table scan versus index lookup: How the database finds rows without an index, An index as a sorted lookup structure, Making a big table with a recursive CTE, Timing a query before and after
        • How a B-tree index works: Sorted keys in a tree of pages, Finding one key in a few steps, Range scans on a B-tree, The clustered primary key in InnoDB
        • Creating indexes: CREATE INDEX on one column, Composite indexes and the leftmost prefix rule, Unique indexes, SHOW INDEX and dropping an index
        • Reading EXPLAIN: EXPLAIN shows the plan, not the result, The type column: ALL, ref, range and const, key, rows and Extra, EXPLAIN FORMAT=TREE
        • EXPLAIN ANALYZE: real timings: EXPLAIN ANALYZE runs the query (MySQL 8.0.18 and later), Estimated versus actual rows, ANALYZE TABLE and statistics, Finding the slow step
        • When an index is not used: Small tables and many matching rows, Functions on the column, Leading wildcards in LIKE, Type mismatches and OR conditions, Covering indexes
        • The cost of indexes on writes: Every index slows INSERT, UPDATE and DELETE, Index size on disk, Unused and duplicate indexes, Choosing indexes from real queries
        • Practice: indexes and query plans: Choose indexes for given queries, Read and compare plans, Fix queries that cannot use an index, Mixed review
        • Mini project: speed up ShopLite queries: A large ShopLite dataset generated with SQL, Five slow queries from the team, Add indexes and prove the speed-up with EXPLAIN ANALYZE, Write a short tuning report
      • Transactions & ACID

      • SQL Practice, ShopLite & PostgreSQL

        • ShopLite project 1: requirements and schema design: Read the ShopLite requirements, Entities: customers, addresses, categories, products, orders and order items, ER diagram and normalisation check, Keys, constraints and DECIMAL for money
        • ShopLite project 2: CREATE script and seed data: One script that builds the whole database, Seed data that tests every rule, Re-runnable scripts with DROP ... IF EXISTS, Checking constraints with bad data
        • ShopLite project 3: business report queries: Sales, customer and product reports, Joins, grouping and window functions together, Views for the dashboard, Indexes for the slowest reports
        • Backups with mysqldump and restoring: Why backups matter, mysqldump for one database and one table, Restoring with the mysql client and SOURCE, Exporting a table to CSV from Workbench
        • SQL interview problem set: Twenty interview problems on the practice data, Joins, grouping, subqueries and window functions mixed, Explaining your answer aloud, Common follow-up questions
        • PostgreSQL for MySQL users: what changes: Install PostgreSQL or run it with Docker, and connect with psql, Identity columns instead of AUTO_INCREMENT, and RETURNING, ON CONFLICT instead of ON DUPLICATE KEY, ILIKE, and stricter types, FULL OUTER JOIN, case-sensitive text and other differences
        • ShopLite project 4: ShopLite on PostgreSQL: Port the ShopLite CREATE script to PostgreSQL, Load the seed data and fix type differences, Run the business reports on PostgreSQL, Write a short MySQL versus PostgreSQL comparison
    2. JDBC & Database Connectivity

      Set up Maven projects and connect Java to a database with JDBC: queries, prepared statements, transactions and the DAO pattern.

      • Maven Projects & Dependencies

        • What a build tool does and why Maven: Compiling by hand with javac and java -cp: what breaks as a project grows, Copying JAR files around: versions, missing transitive JARs, 'works on my machine', What Maven does: one project file, downloads libraries, runs the same build everywhere, Convention over configuration: the standard folder layout Maven expects, Installing Maven and checking it with mvn -v (Windows and macOS)
        • Create a Maven project in your IDE and from the terminal: New Maven project in IntelliJ IDEA: the wizard fields and what they become, mvn archetype:generate with maven-archetype-quickstart from the terminal, The standard layout: src/main/java, src/main/resources, src/test/java, target, Packages that match folders: com.shoplite.app and where Main.java lives, Opening an existing Maven project and reloading it after pom changes
        • pom.xml: coordinates, packaging and properties: Reading a minimal pom.xml line by line, Coordinates: groupId, artifactId and version, and why together they identify a library, SNAPSHOT versus release versions, packaging: jar (default) and when you would see war or pom, properties: maven.compiler.release 17 and project.build.sourceEncoding UTF-8
        • Adding dependencies and the local repository: Finding a library on Maven Central and copying its dependency block, Where downloads go: the local repository ~/.m2/repository, Scopes: compile, runtime, test and provided, with JUnit and the MySQL driver as examples, Transitive dependencies and reading mvn dependency:tree, Errors: 'Could not resolve dependencies', typos in coordinates, offline builds
        • The build lifecycle: compile, test, package: Phases in order: validate, compile, test, package, verify, install, Running a phase runs every phase before it: what mvn package actually does, mvn clean and what lives in target/, Plugins and goals: the compiler and surefire plugins behind the phases, A failing JUnit test stops the build, and reading the surefire report
        • Running your app and building a JAR: Running Main from the IDE versus from the terminal, mvn exec:java with the exec-maven-plugin and a mainClass, Building a JAR with mvn package and running it with java -jar, 'no main manifest attribute' and setting Main-Class in the jar plugin, A runnable JAR that includes its dependencies with the shade plugin
        • Maven vs Gradle in one lesson: The same project as pom.xml and as build.gradle.kts, Shared ideas: coordinates, Maven Central, dependency scopes and configurations, Wrappers: mvnw and gradlew so everyone uses the same version, Where each is used in industry and why this course uses Maven, Reading a Gradle build well enough to run someone else's project
        • Practice: Maven projects: Write a pom.xml for a given project description, Choose the right scope for each dependency, Predict which phases a command runs, Fix broken builds: wrong coordinates, missing Main-Class, failing test, Interview drill: Maven questions
        • Mini project: the shoplite-console Maven project: Create shoplite-console with groupId com.shoplite and Java 17, Packages model, dao, service, config and app with a placeholder Main, JUnit 5 as a test dependency and one passing test, exec plugin and a runnable JAR, .gitignore for target/ and secrets, a README and the first commit on GitHub
      • Connecting to a Database

        • What JDBC is: API and driver: The problem: one Java program, many database products, The JDBC API in java.sql: interfaces such as Connection, Statement and ResultSet, The driver: a vendor library that implements those interfaces (mysql-connector-j), The path of a query: Java code, driver, network, MySQL server and back, The four steps every JDBC program follows: connect, send SQL, read results, close
        • Adding the MySQL driver with Maven: The com.mysql:mysql-connector-j dependency and choosing its version, Why the driver can use runtime scope: code compiles against java.sql only, Automatic driver loading through ServiceLoader, and why Class.forName is no longer needed, 'No suitable driver found': missing dependency or a mistyped URL, Checking the driver is on the classpath with dependency:tree
        • JDBC URL, user and password: Reading jdbc:mysql://localhost:3306/shoplite part by part, Useful URL parameters: serverTimezone, characterEncoding and sslMode, Creating the shoplite database from the SQL section's script, A dedicated application user with CREATE USER and GRANT instead of root, Checking the same URL, user and password work in the mysql client first
        • DriverManager and Connection: DriverManager.getConnection(url, user, password) and what it returns, Checking the connection: isValid, getCatalog and DatabaseMetaData product version, Closing the connection, and a first look at try-with-resources, Connection refused / Communications link failure: server not running, wrong host or port, Access denied for user, Unknown database and public key retrieval errors, read from the message
        • Keeping credentials out of code: Why a password in source code ends up on GitHub and stays in history, Reading DB_URL, DB_USER and DB_PASSWORD with System.getenv (Windows and macOS), A db.properties file loaded from the classpath with Properties, Committing db.properties.example and listing the real file in .gitignore, Failing fast with a clear message when a setting is missing
        • Practice: connecting to a database: Write JDBC URLs for given hosts, ports and databases, Match error messages to their causes, Fix programs with hard-coded or missing settings, Print database details with DatabaseMetaData, Interview drill: JDBC basics
        • Mini project: connect shoplite-console to MySQL: Create the ShopLite schema and seed data from the SQL section, A DatabaseConfig class in com.shoplite.config reading environment variables or db.properties, A ConnectionFactory that opens connections from that config, A startup health check printing the MySQL version and the row count of each table, Clear messages for a missing setting or an unreachable server, and a committed example config
      • Running Queries with JDBC

        • Statement and executeQuery: connection.createStatement() and statement.executeQuery(sql), Running SELECT name, price FROM product from Java, executeQuery, executeUpdate and execute: which one for which SQL, SQL syntax errors from Java: reading the error and the failing SQL, Why Statement is only for fixed SQL (user input waits for prepared statements)
        • Reading a ResultSet row by row: The cursor: starts before the first row, next() moves and returns false at the end, getString, getInt and friends by column label versus by index, Column aliases and joined queries: reading the label you chose, An empty result, and reading exactly one row with if (rs.next()), 'Column not found' and 'Before start of result set' errors
        • Column types to Java types, dates and NULL: INT and BIGINT to int and long, VARCHAR to String, BOOLEAN/TINYINT(1) to boolean, DECIMAL to BigDecimal with getBigDecimal: why money is never double, DATE, DATETIME and TIMESTAMP to LocalDate and LocalDateTime with getObject(col, Type.class), NULL columns: getInt returns 0, and wasNull or getObject(col, Integer.class) to tell, A type-mapping table to keep next to your code
        • executeUpdate for INSERT, UPDATE and DELETE: executeUpdate returns the number of affected rows, Inserting a category and updating a product price from Java, Checking for 0 rows: the row you wanted to change did not exist, DELETE and foreign keys: the constraint error when an order references a product, Duplicate key errors on unique columns such as customer email
        • Mapping rows to your own classes and records: A Product record that matches the product table, One mapRow(ResultSet) method used by every query, Building a List<Product> and returning Optional<Product> for one row, A RowMapper<T> functional interface and a lambda per entity, Records versus classes for entities, and keeping column names in one place
        • Practice: running queries with JDBC: Read query results into records, Map dates, money and NULL columns correctly, Check affected row counts, Fix wrong getters, cursor mistakes and lost NULLs, Interview drill: Statement and ResultSet
        • Mini project: ShopLite catalog reports: Product and Category records in com.shoplite.model, List all categories and all products with their category name, Low-stock report and products never ordered, Prices as BigDecimal and dates as LocalDateTime throughout, A simple console menu in com.shoplite.app to choose a report
      • Prepared Statements & SQL Injection

        • SQL injection demonstrated on a login query: Building SQL with string concatenation from user input, Logging in without a password with ' OR '1'='1 and with a -- comment, Reading other tables through injected input, Why escaping quotes by hand is not a fix, Real-world impact and why interviewers always ask about it
        • PreparedStatement and ? placeholders: connection.prepareStatement(sql) with ? placeholders, setString and the 1-based parameter index, The same login attack against the prepared version: it fails, Values only: table names, column names and ORDER BY cannot be parameters, so use an allow-list, 'Parameter index out of range' and 'No value specified for parameter' errors
        • Setting parameters of each type: setInt, setLong, setBigDecimal and setBoolean, Dates and times with setObject(index, LocalDate/LocalDateTime), setNull with a java.sql.Types constant for optional values, LIKE searches: the % goes into the parameter value, not the SQL, IN lists: building one ? per value
        • Getting generated keys after INSERT: AUTO_INCREMENT ids and why the program needs the new id, prepareStatement(sql, Statement.RETURN_GENERATED_KEYS), Reading getGeneratedKeys() after executeUpdate, Returning the saved record with its id, Using the new id for a child row: an order and its first item
        • Batch inserts with addBatch: One round trip per row versus one batch, addBatch, executeBatch and the int[] of row counts, rewriteBatchedStatements=true in the MySQL URL and a timing comparison, Large imports in chunks of a few hundred rows, BatchUpdateException: which rows failed and why
        • Practice: prepared statements: Convert injectable queries to prepared statements, Bind dates, money, NULL and LIKE patterns, Use generated keys and batches, Find and fix injection holes in a code review, Interview drill: Statement vs PreparedStatement and SQL injection
        • Mini project: customer sign-up, product search and bulk import: Register a customer and print the generated id, Search products by name and filter by category and price range with parameters, Sort by an allow-listed column chosen from the menu, Import products from a CSV file with a batch insert, Every query parameterised: no string-built SQL left
      • Resource Handling & SQL Errors

        • Why unclosed connections break applications: What a connection holds on the server: a thread, memory, a slot in max_connections, A loop that leaks connections until 'Too many connections', Watching open connections with SHOW PROCESSLIST, Open statements and result sets also hold resources, The old way: close calls in finally blocks and why they are easy to get wrong
        • try-with-resources for Connection, Statement and ResultSet: Declaring Connection, PreparedStatement and ResultSet in one try, Closing order: reverse of opening, done for you, A nested try for the ResultSet when parameters must be set first, Suppressed exceptions when close also fails, Returning results safely from inside a try block
        • SQLException, SQL state and error codes: getMessage, getSQLState and getErrorCode on one real failure, MySQL codes you will meet: 1062 duplicate entry, 1452 and 1451 foreign key, 1045 access denied, 1146 unknown table, SQL state classes: 23xxx constraint, 08xxx connection, 42xxx syntax, Subclasses such as SQLIntegrityConstraintViolationException and SQLTransientConnectionException, Chained exceptions and the cause
        • Turning SQL errors into meaningful application exceptions: Why callers should not deal with checked SQLException, An unchecked DataAccessException that keeps the original as its cause, Specific exceptions: DuplicateEmailException, ProductNotFoundException, Never swallowing exceptions: catch, translate, rethrow, Messages for users versus details for logs
        • Practice: resources and SQL errors: Find the leak in given JDBC methods, Rewrite cleanup with try-with-resources, Classify SQLExceptions by state and code, Design exception types for a small app, Interview drill: resource handling and exceptions
        • Mini project: leak-free ShopLite with clear errors: Every query in shoplite-console moved to try-with-resources, A DataAccessException hierarchy in com.shoplite.dao, Duplicate email on sign-up and deleting a product that has orders reported clearly, The menu keeps running after an error, A leak check: run every menu option many times and watch SHOW PROCESSLIST
      • Transactions in JDBC

        • Auto-commit and turning it off: Auto-commit on by default: every statement is its own transaction, A half-finished change when the second statement fails, setAutoCommit(false) to group statements, What happens to uncommitted work when the connection closes, One transaction means one connection: why both statements must share it
        • commit and rollback in a try/catch: The standard shape: setAutoCommit(false), work, commit, rollback in catch, Rolling back on any exception, not only SQLException, Restoring auto-commit before the connection is reused, Savepoints: rolling back part of a transaction, A transfer between two accounts as the worked example
        • Placing an order: stock update plus order insert: The steps: insert the order, insert each item, reduce stock, set the total, Generated order id reused for the order items, Reducing stock with UPDATE ... WHERE stock >= ? and checking the row count, Out of stock: throw, roll back, and nothing is saved, Checking the result in MySQL after a success and after a failure
        • Setting the isolation level: Recap: dirty reads, non-repeatable reads and phantoms, setTransactionIsolation and the Connection.TRANSACTION_* constants, MySQL InnoDB's default REPEATABLE READ and what it guarantees, Two connections side by side showing the difference between levels, Why most apps keep the default and lock specific rows instead
        • Preventing overselling with SELECT ... FOR UPDATE: Two threads buying the last item: the lost-update race reproduced, SELECT ... FOR UPDATE locks the rows until commit, The single conditional UPDATE as an alternative, and when each fits, Deadlocks (error 1213) and lock wait timeouts (error 1205): what they mean, Locking rows in a fixed order and retrying a deadlocked transaction
        • Practice: transactions in JDBC: Wrap multi-step changes in transactions, Fix transactions that forget rollback or use two connections, Predict results under different isolation levels, Make a race-prone update safe, Interview drill: ACID, isolation and locking from Java
        • Mini project: placing ShopLite orders safely: An OrderService.placeOrder method in com.shoplite.service, Order, items, stock and total saved in one transaction, Clear OutOfStockException and full rollback, Row locks so concurrent orders never oversell, A test that runs two buyers at once and checks the final stock
      • The DAO Pattern

        • Why mixing SQL with business logic hurts: A menu method that opens connections, builds SQL, applies rules and prints, What goes wrong: duplication, no tests without a database, changes ripple everywhere, Layers: app (input/output), service (rules), dao (SQL), model (data), Each layer only calls the one below it, Where each ShopLite class will live
        • DAO interface and JDBC implementation: A ProductDao interface: findById, findAll, save, update, delete, JdbcProductDao implementing it with prepared statements and a row mapper, Optional for lookups, the saved entity with its id for inserts, Getting connections from a ConnectionFactory passed in the constructor, Translating SQLException inside the DAO so callers never see it
        • Entity classes vs DTOs: An entity mirrors a table row: Product, Customer, Order, A DTO carries exactly what a screen or report needs: OrderSummary, SalesByCategory, Report queries that map straight into DTO records, Input DTOs such as NewCustomer without an id, Where mapping between entities and DTOs happens
        • A service layer on top of DAOs: Business rules in services: validation, stock checks, totals, Constructor injection: services receive their DAOs, wired once in Main, Transactions that span several DAOs: one connection shared through the call, A small TransactionManager helper that commits or rolls back, Services throw domain exceptions; the app layer turns them into messages
        • Paging results with LIMIT and OFFSET from Java: Why findAll without a limit fails once data grows, LIMIT ? OFFSET ? with page number and page size parameters, A Page<T> record with items, page, size and total count, A stable ORDER BY so pages never repeat or skip rows, Validating page input and the cost of large offsets
        • Swapping implementations behind an interface: An InMemoryProductDao built on a Map, Running the same service with the JDBC or the in-memory DAO, JUnit 5 tests of the service with a fake DAO, no database needed, Why depending on interfaces makes code easy to change, How this prepares for Spring repositories later in the course
        • Practice: the DAO pattern: Write a DAO for a given table, Move business rules out of DAOs into services, Design entity and DTO records, Add paging to a list query, Interview drill: DAO, service layer and DTOs
        • Mini project: the ShopLite DAO and service layers: ProductDao, CategoryDao, CustomerDao and OrderDao with JDBC implementations, ProductService, CustomerService and OrderService with constructor injection, The order transaction moved into OrderService across DAOs, Paged product listing in the menu, Service unit tests with in-memory DAOs
      • Connection Pooling & Configuration

        • Why opening a connection per query is slow: What happens when a connection opens: network, handshake, login, session setup, Timing 100 queries with a new connection each versus one reused connection, The pool idea: borrow, use, give back, close() on a pooled connection returns it instead of closing it, A pool also limits how many connections hit the database
        • DataSource vs DriverManager: The javax.sql.DataSource interface and getConnection(), MysqlDataSource as a simple, non-pooled DataSource, Code that depends on DataSource does not care whether it is pooled, Replacing the ConnectionFactory with a DataSource in DAOs, Why frameworks such as Spring always hand you a DataSource
        • HikariCP setup and key settings: Adding com.zaxxer:HikariCP and creating a HikariDataSource from HikariConfig, maximumPoolSize and minimumIdle: sizing a small pool, connectionTimeout, idleTimeout and maxLifetime, Pool exhausted ('Connection is not available, request timed out') and leakDetectionThreshold, Closing the pool on shutdown with a shutdown hook
        • Loading configuration from a properties file: application.properties on the classpath for non-secret settings, Environment variables override file values for secrets and per-machine settings, An immutable AppConfig record built once at startup, Validating required values and number formats with clear errors, Committing application.properties.example, ignoring the real file
        • Running SQL scripts at startup: schema.sql and seed.sql in src/main/resources, Reading a script from the classpath and running it statement by statement, Idempotent scripts: CREATE TABLE IF NOT EXISTS and safe seed inserts, Running scripts only when a setting such as db.init=true is on, Why real projects use migration tools (Flyway, later in the course)
        • Practice: connection pooling and configuration: Convert DriverManager code to a pooled DataSource, Choose pool settings for given scenarios, Fix configuration loading bugs, Find the leak that exhausts a pool, Interview drill: connection pools and DataSource
        • Mini project: pooled, configurable shoplite-console: AppConfig in com.shoplite.config from application.properties and environment variables, A HikariDataSource shared by every DAO, Optional schema and seed scripts at startup, Pool closed cleanly on exit, README section on configuring and running the app
      • JDBC Mini Project: ShopLite Console App

        • ShopLite console app: structure and plan: The finished feature list and the menu tree, Packages model, dao, service, config and app and what each may depend on, Wiring everything once in Main: config, DataSource, DAOs, services, menu, A menu loop with small command handlers instead of one giant switch, Input reading and validation helpers shared by every screen
        • Milestone project: product and customer management: Add, edit, list (paged) and search products; manage categories, Adjust stock and deactivate products that already have orders, Register and update customers with unique email checks, Validated input with re-prompts on bad values, Service tests for the catalog and customer rules
        • Milestone project: placing orders and order history: A cart built in memory and placed as one transaction, Stock locking so concurrent orders never oversell, Order status changes such as cancel with stock restored, Order history for a customer with items and totals, Clear messages for out-of-stock, unknown product and unknown customer
        • Practice: JDBC section review: Mixed exercises across Maven, JDBC queries, prepared statements and transactions, Code review: find injection, leaks, missing rollback and logic in the wrong layer, Report queries mapped into DTOs, Explain your ShopLite design choices, Interview drill: full JDBC round
        • Milestone project: sales reports and release on GitHub: Sales reports: revenue by day, top products and sales by category as DTOs, Customers who never ordered and low-stock alerts, Final pass on error messages and input validation across all screens, Runnable JAR, application.properties.example and setup scripts, README with features, setup, configuration and sample run, pushed to GitHub
    3. Web Fundamentals, HTTP & REST APIs

      How the web works: HTTP, JSON and the rules of good REST API design, tested with real tools.

      • How the Web Works

        • Clients and servers: A client asks, a server answers: the request-response cycle, Browsers, mobile apps, curl and other programs as clients, One server, many clients at the same time; one machine can run many servers, Web pages versus APIs: HTML for people, JSON for programs, localhost: running client and server on the same machine
        • IP addresses, ports and DNS: IP addresses: IPv4 and IPv6, public and private, 127.0.0.1 and ::1, Ports: one address, many services (80, 443, 3306, 8080), DNS turns a name into an address: resolver, cache and TTL, Looking up a name with nslookup (Windows) and dig (macOS), The hosts file, and what 'could not resolve host' and 'connection refused' mean
        • URLs: scheme, host, port, path and query: Taking a URL apart: scheme://host:port/path?query#fragment, Default ports for http and https, and when the port is shown, Query strings: key=value pairs joined with &, repeated keys, Percent-encoding: spaces, &, ? and non-English characters, Absolute versus relative URLs, and the fragment never reaching the server
        • TCP: the connection under HTTP: Network layers in one picture: IP, TCP, TLS, HTTP, TCP gives a reliable, ordered byte stream; the three-way handshake, HTTP is just text sent over that stream: a raw request typed by hand, Keep-alive connections, and HTTP/1.1 versus HTTP/2 and HTTP/3 in one paragraph, Timeouts and 'connection reset': what failed and where
        • HTTPS and TLS in plain words: What TLS protects: privacy, integrity and proving the server's identity, The TLS handshake in plain words: certificates, keys and a shared secret, Certificates, certificate authorities and the browser padlock, Certificate errors: expired, wrong host name, self-signed, Why every API, even a test one, should use HTTPS; never disable certificate checks
        • Watching requests in browser dev tools: Opening the Network tab; Preserve log and Disable cache, One page load is many requests: HTML, CSS, scripts, images, API calls, Inspecting a request: URL, method, status, headers, payload, response, The Timing view: DNS, connect, TLS, waiting and download, Filtering to Fetch/XHR, and 'Copy as cURL' to replay a request
        • Practice: how the web works: Take apart tricky URLs and fix badly encoded ones, Put the steps from typing a URL to seeing a page in order, Match error messages to the layer that failed, Interview drill: 'what happens when you type a URL and press Enter'
        • Mini project: trace a web request end to end: Resolve a real site's name and note its addresses, Fetch it with curl -v and label every line: DNS, connect, TLS, request, response, Record the same page load in dev tools and export a HAR file, Write a request-trace report (README) explaining each step in your own words
      • HTTP Requests & Responses

        • Request line, headers and body: The request line: method, target and version, Headers: case-insensitive name: value lines, and the required Host header, The blank line, then an optional body; Content-Length tells its size, The response: status line, headers and body, Reading a full request and response pair line by line
        • GET, POST, PUT, PATCH and DELETE: GET reads, with no body and parameters in the URL, POST creates or triggers an action, with a body, PUT replaces a whole resource; PATCH changes part of it, DELETE removes; HEAD and OPTIONS in one line each, Picking the method for real actions: search, add to cart, update stock, cancel order
        • Safe and idempotent methods: Safe: the request changes nothing on the server, Idempotent: sending it twice has the same effect as once, The table: GET, HEAD, PUT, DELETE are idempotent; POST and PATCH are not, Why it matters: retries after a timeout, double-clicked buttons, browser refresh, Making POST safe to retry with an idempotency key (the idea)
        • Status code families: 2xx, 3xx, 4xx and 5xx: The five families and what each one tells the client, 2xx: 200 OK, 201 Created, 204 No Content, 3xx: 301, 302, 304 Not Modified and how redirects are followed, 4xx client mistakes: 400, 401, 403, 404, 405, 409, 415, 422, 429, 5xx server failures: 500, 502, 503, 504, and who must fix what
        • Important headers: Content-Type, Accept, Authorization, Location: Content-Type and charset: what the body is (application/json; charset=utf-8), Accept and content negotiation; 406 and 415 when they don't match, Authorization: Basic and Bearer schemes, and why only over HTTPS, Location after 201 Created and on redirects, Other headers you will meet: Content-Length, Cache-Control, User-Agent, custom X- headers
        • Sending requests with curl: Installing and checking curl on Windows (curl.exe, not the PowerShell alias) and macOS, A GET request; -i to see headers and -v to see everything, -X for the method, -H for headers, -d and --json for a body, Quoting JSON on Windows versus macOS, and reading a body from a file with @, -L to follow redirects, -s and -o to keep output clean
        • Practice: HTTP requests and responses: Label the parts of raw requests and responses, Choose methods and status codes for given scenarios, Fix broken curl commands and wrong headers, Interview drill: PUT vs PATCH, 401 vs 403, idempotency
        • Mini project: explore a public API with curl: Pick a free public JSON API and list its endpoints, Script GET, POST, PUT, PATCH and DELETE calls with curl, saving each response, Record status codes and key headers for every call in a table, Trigger and explain 404, 405 and 400 responses on purpose
      • State, Cookies & Sessions

        • Why HTTP is stateless: Every request stands alone: the server keeps no memory between them, Why that is good: simple servers, easy scaling behind a load balancer, The problem: logins and shopping carts need to be remembered, Three answers: cookies, server-side sessions and tokens, Where state can live: client, server memory, database or cache
        • Cookies: how they are set and sent: Set-Cookie in a response, Cookie in every later request, Lifetime: session cookies versus Expires and Max-Age, Scope: Domain and Path, Security attributes: HttpOnly, Secure and SameSite, Seeing cookies in dev tools and keeping them with curl -c and -b
        • Server-side sessions: A session id in a cookie, the data on the server, The login flow step by step: credentials, session created, cookie set, Logout and expiry: destroying the session, Sessions with several servers: sticky sessions or a shared store, Risks in one line each: session hijacking, fixation, CSRF, and their fixes
        • Tokens in headers as an alternative: Login returns a token; the client sends Authorization: Bearer on each request, What a JWT looks like: header, payload, signature (signed, not encrypted), Sessions versus tokens: where state lives, logout, scaling, mobile clients, Where clients keep tokens and the risks of each place, Expiry and refresh tokens in one picture (built for real in Section 17)
        • Same-origin policy and CORS (the idea): An origin is scheme + host + port; same-origin examples and counter-examples, What the browser blocks and why: protecting your logged-in cookies, CORS: the server opts in with Access-Control-Allow-Origin, Preflight OPTIONS requests for JSON bodies and custom headers, Reading a CORS error in the console, and why curl and Postman never see it
        • Practice: cookies, sessions and tokens: Pick cookie attributes for given cases, Decide same-origin or cross-origin for pairs of URLs, Compare session and token designs for a web and a mobile app, Interview drill: cookies vs sessions vs JWT, what CORS protects
        • Mini project: follow a login with curl: Set, read and delete cookies on a public test service with a curl cookie jar, Call an endpoint that needs a Bearer token, with and without it (401), Watch a real site's login cookies in dev tools and list their attributes, Write a README comparing what the session and token flows sent on the wire
      • JSON & Jackson

        • JSON syntax: objects, arrays and types: Objects, arrays and the six value types (string, number, boolean, null, object, array), Rules that break JSON: single quotes, trailing commas, comments, unquoted keys, Nesting: a ShopLite order with its customer and items, Numbers and money: why prices travel as exact decimals or strings, dates as ISO-8601 strings, Validating and pretty-printing JSON, and reading a parse error position
        • Adding Jackson with Maven: jackson-databind and the two libraries it brings with it, Jackson 3 (tools.jackson packages) versus Jackson 2 (com.fasterxml) in older code, Adding the dependency and checking it with mvn dependency:tree, A first JsonMapper call to prove the setup works, Fixing 'package does not exist' and version clashes
        • ObjectMapper: object to JSON and back: Building one shared, thread-safe JsonMapper and reusing it, writeValueAsString and pretty printing, readValue from a String, a file and an InputStream, What Jackson needs from a class: getters, setters and a no-arg constructor, Reading the exception when JSON and the class don't match
        • Lists, maps and nested objects: Serializing a List of products to a JSON array, Reading a JSON array back: why List.class loses the type, and TypeReference, Nested objects: an order with its customer and a list of items, Maps and the JsonNode tree for JSON whose shape you don't know, Reading one value deep inside a response with path() and get()
        • Records, dates and money: Records as DTOs: Jackson reads and writes them with no extra code, LocalDate, LocalDateTime and Instant as ISO-8601 strings, not number arrays, Time zones and offsets in JSON timestamps, BigDecimal prices: keeping exact values, Enums such as order status as JSON strings
        • Renaming and ignoring fields with annotations: @JsonProperty: snake_case JSON names on camelCase fields, @JsonIgnore: keeping secrets such as password hashes out of JSON, @JsonInclude(NON_NULL): leaving out empty fields, @JsonFormat for a custom date pattern, Naming strategies on the mapper versus per-field annotations
        • Handling unknown or missing fields: Unknown properties: failing versus ignoring, per class and per mapper, Missing fields become null or zero, and how to detect that, null for primitives, wrong types and malformed JSON: the exceptions you get, Checking required fields yourself after reading, Tolerant reader: why API clients should ignore fields they don't know
        • Practice: JSON and Jackson: Fix invalid JSON documents, Map given JSON to records and back, Fix broken mappings: missing constructor, wrong generic type, date as array, Interview drill: ObjectMapper reuse, @JsonIgnore, unknown properties
        • Mini project: ShopLite catalogue to JSON and back: Add Jackson to shoplite-console and a shared JsonMapper in .config, JSON records (ProductJson, CategoryJson) kept separate from the model classes, Export the catalogue from the Section 13 service layer to products.json, Import products.json back, with validation and clear errors for bad files
      • REST API Design

        • Resources and nouns in URLs: What REST means in practice: resources, representations, stateless requests, Nouns not verbs: /products, not /getProducts, Collections and items: /products and /products/{id}, plural names, URL style: lowercase, hyphens, no file extensions, ids in the path, Actions that are not CRUD: modelling 'cancel order' as a resource or sub-resource
        • Mapping CRUD to methods and status codes: List and read: GET, 200, or 404 for a missing item, Create: POST to the collection, 201 with Location and the created body, Update: PUT or PATCH, 200 with the body or 204, Delete: 204, and what a second DELETE returns, Errors on writes: 400 bad input, 409 conflict, 422 rule broken
        • Nested resources: /customers/{id}/orders: Child resources that belong to a parent, /customers/{id}/orders versus /orders?customerId=, Keeping nesting to one level, 404 for a missing parent versus an empty list, Order items: /orders/{id}/items
        • Filtering, sorting and pagination with query parameters: Filters as query parameters: ?category=books&minPrice=100, Sorting: ?sort=price,desc and allowed sort fields, Page and size pagination with a maximum page size, The page envelope: content, page, size, totalElements, totalPages, Offset versus cursor pagination, and the Link header
        • Consistent error response format: Why one error shape for the whole API, Problem Details (RFC 9457): type, title, status, detail, instance, Validation errors: a list of field and message pairs, application/problem+json and the matching status code, Never leak stack traces, SQL or internal ids in errors
        • API versioning: Breaking versus non-breaking changes, Version in the path (/api/v1), in a header or in the media type, Adding fields safely and deprecating old ones, Running two versions side by side, The choice for ShopLite: /api/v1 and why
        • Practice: REST API design: Design endpoints for small requirements (library, blog, bookings), Fix bad URLs, methods and status codes, Write example requests and responses, including errors, Interview drill: REST principles, PUT vs POST, pagination, versioning
        • Project: design the ShopLite API on paper: Resources from the ShopLite schema: categories, products, customers, orders, order items, Endpoint table under /api/v1: method, URL, request body, success and error statuses, Request and response JSON for every endpoint, with money and dates done right, List rules (filters, sort, page size limit) and the Problem Details error format, API-DESIGN.md committed to the repo as the contract for Sections 14 to 17
      • Testing APIs with Tools

        • Postman: your first requests: Installing Postman and creating a workspace, Building a GET request: URL, query params table, Send, Reading the response: status, time, size, body, headers, History, and saving a request, Postman alternatives in one line: Bruno, Insomnia, IDE HTTP clients
        • Sending JSON bodies and headers: Raw JSON body and the Content-Type header Postman adds, Custom headers and the hidden auto-generated ones, The Authorization tab: Bearer token and Basic auth, PUT, PATCH and DELETE requests, Fixing 415 and 400 responses caused by the wrong body type
        • Postman collections and environments: Collections and folders to organise an API's requests, Variables: {{baseUrl}}, collection versus environment scope, Local and production environments, and secret values kept out of exports, Passing an id from one response to the next request, Exporting a collection to commit it with the project
        • Saving tests in a collection: Post-response scripts: pm.test and pm.expect, Checking status, headers, response time and JSON fields, Saving values into variables from scripts, Running a whole collection in order with the Collection Runner, Running collections from the command line with Newman (the idea)
        • curl recipes for daily use: JSON writes: --json, -d @body.json, and headers, Auth: -u for Basic, -H for Bearer, tokens from environment variables, Printing only the status code and timing with -w, failing on errors with --fail, Downloading files, following redirects, cookies and retries, Pretty-printing JSON output and saving reusable curl scripts per OS
        • Reading an API's documentation: What good docs contain: base URL, auth, endpoints, examples, errors, OpenAPI and Swagger UI: reading schemas and trying calls, Rate limits, 429 and Retry-After, API keys: getting one and keeping it out of Git, Importing an OpenAPI spec into Postman
        • Practice: testing APIs with tools: Translate between Postman requests and curl commands, Write tests for given responses, Fix broken requests, variables and scripts, Interview drill: how do you test an API manually and automatically
        • Mini project: a tested Postman collection for a public API: Read a public API's docs and choose its main endpoints, Build a collection with folders, an environment and chained requests, Add tests for status codes, fields and error cases; run them in the runner, Commit the exported collection plus a matching curl script and README
      • Calling APIs from Java

        • HttpClient, HttpRequest and HttpResponse: java.net.http: the three types and how they fit together, Building one reusable HttpClient, A GET with HttpRequest.newBuilder and send, BodyHandlers.ofString and reading status, headers and body, sendAsync and CompletableFuture in one example
        • GET and POST with JSON: Setting Accept and Content-Type headers, POST with BodyPublishers.ofString and a Jackson-written body, PUT, PATCH (method("PATCH", ...)) and DELETE, Query parameters and safe URL encoding with URLEncoder, Reading the Location header after 201 Created
        • Timeouts and checking status codes: Connect timeout on the client, request timeout on each request, Why the default 'wait forever' is dangerous, Checking statusCode before using the body, Redirect policy and HTTP version settings, Turning 4xx and 5xx responses into meaningful exceptions
        • Parsing responses with Jackson: Mapping a JSON body to a record, Lists and paged responses with TypeReference, Reading a Problem Details error body into an error record, Ignoring unknown fields so API additions don't break you, Wrapping it all in a small typed API client class
        • Handling network failures: What can fail: unknown host, connection refused, TLS errors, timeouts, The exceptions: IOException, ConnectException, HttpTimeoutException, InterruptedException, Restoring the interrupt flag and never swallowing exceptions, Retrying only idempotent requests, with backoff and a limit, A clear exception type for callers and useful error messages
        • Practice: calling APIs from Java: Write GET and POST calls for given endpoints, Map responses and error bodies to records, Fix clients with missing timeouts, unchecked status or swallowed exceptions, Interview drill: HttpClient reuse, timeouts, retries and idempotency
        • Mini project: exchange-rate client for ShopLite prices: A RatesClient in shoplite-console calling a free exchange-rate API, Records for the response, BigDecimal conversion with proper rounding, Timeouts, status checks, a custom exception and a cached last result, Show catalogue prices in another currency from the console menu
      • A Tiny HTTP Server Without a Framework

        • Starting an HttpServer and adding handlers: The jdk.httpserver module: HttpServer, HttpHandler, HttpExchange, create, createContext, start, and a first 'hello' handler, sendResponseHeaders, the response length rules and closing the exchange, Testing it with curl and the browser, 'Address already in use' and other startup errors
        • Routing by method and path by hand: Contexts match by prefix: what /api/v1/products really receives, Reading the method, path and query string, Path variables: /products/42 parsed safely, 404 for unknown paths, 405 with an Allow header for wrong methods, A small Router class instead of if-else chains
        • Reading request bodies and writing JSON responses: Reading the request body stream into a record with Jackson, Checking Content-Type and returning 415, Writing JSON with the right Content-Type, charset and length, Query parameters for filters and paging, A small helper for reading and writing JSON
        • Returning the right status codes: 201 with Location, 200 and 204 for the CRUD operations, 400 for malformed JSON or missing fields, 404 and 409 from service-layer exceptions, One catch-all: 500 with a safe Problem Details body and the error logged, Mapping exception types to status codes in one place
        • Wiring the service layer and handling many requests: Handlers call services, never DAOs: reusing the Section 13 layers, Constructing the object graph by hand in a main class, The default single thread versus an executor (virtual threads on Java 21), Thread safety: shared services and the DataSource pool, Graceful stop and configuration from environment variables
        • What Spring Boot will do for you next: Everything we wrote by hand: routing, JSON, errors, wiring, threads, config, The Spring Boot piece that replaces each one, The same endpoint written both ways side by side, What stays the same: your services, DTOs and API design, Why learning the hard way makes framework errors easier to debug
        • Practice: a tiny HTTP server: Add endpoints to a given server, Fix handlers that never close, send wrong lengths or wrong statuses, Write curl tests for every route, Interview drill: what happens inside a web server for one request
        • Project: ShopLite product API on HttpServer: shoplite-http project reusing the Section 13 model, DAO and service code, Categories and products endpoints exactly as in API-DESIGN.md, Paging, filtering, validation and Problem Details errors, curl script and Postman collection that test every endpoint; README
      • Web & REST Practice

        • Practice: design REST endpoints for given requirements: Requirements to resources: a food-delivery and a course-booking API, Endpoint tables with methods, statuses and example bodies, List endpoints with filters, sorting and pages, Error cases and their Problem Details bodies
        • Practice: spot the mistakes in a badly designed API: Verbs in URLs, GET that changes data, 200 for every error, Inconsistent naming, error shapes and date formats, Missing pagination, leaked internal fields and stack traces, Rewriting the API correctly and explaining each fix
        • HTTP and REST interview questions: What happens when you type a URL; HTTP vs HTTPS, Methods, idempotency and status codes, Cookies, sessions, tokens and CORS, REST design, versioning, pagination; Jackson and HttpClient questions
        • Mini project: command-line client for a public API: A Maven CLI that searches a public API (for example GitHub repositories), Typed client with HttpClient, Jackson records, timeouts and error handling, Following pagination and respecting rate limits, Commands, readable output, an API token from an environment variable, and a README
        • Milestone project: ShopLite REST API and Java client: Add customers and orders endpoints (/customers/{id}/orders, place and cancel an order) to the HttpServer API, Placing an order runs in one service-layer transaction with stock checks and 409 on conflicts, shoplite-client: a typed Java HttpClient + Jackson client and console menu for the API, Full Postman collection with tests, curl script, API-DESIGN.md kept in sync, README
    4. Spring Framework & Spring Boot

      Dependency injection, Spring Boot applications, REST controllers, validation, error handling and configuration.

      • Why Spring?

        • Tight coupling and the new keyword: An OrderService that calls new EmailNotifier() inside its method, Why it is hard to switch to SMS or to test without sending real email, Coding to an interface still leaves the new inside the class, The plain-Java fix: pass the dependency in through the constructor, Tight vs loose coupling side by side in one small program
        • Inversion of control in plain words: Who creates the objects: the class itself or someone outside, Wiring the whole app by hand in main (the composition root), Why hand wiring gets painful as the app grows, A container that creates and connects objects for you, IoC (the idea) vs dependency injection (the technique)
        • Spring Framework vs Spring Boot: Spring Framework: the container, Web MVC, JDBC support and transactions, Spring Boot: starters, auto-configuration, embedded server and sensible defaults, The wider family: Spring Data, Spring Security, Spring Cloud, Versions used in this course: Spring Boot 4.1, Spring Framework 7, Jakarta EE 11, Java 17+, javax to jakarta: why old tutorials' imports do not compile
        • Creating a project with Spring Initializr: start.spring.io fields: Maven, Java 17, Boot 4.1.x, group com.shoplite, artifact shoplite-api, Jar, Choosing dependencies: Spring Web MVC to start, more later, Opening the project in IntelliJ IDEA or VS Code, Running with the Maven wrapper: mvnw spring-boot:run on Windows and macOS, First-run problems: wrong JDK version and port 8080 already in use
        • Project layout and the main class: pom.xml: spring-boot-starter-parent, java.version and the spring-boot-maven-plugin, src/main/java, src/main/resources/application.properties, static and templates, The main class: @SpringBootApplication and SpringApplication.run, Why the main class sits in the root package com.shoplite, Packaging a runnable jar with mvnw package and running it with java -jar
        • Practice: why Spring: Refactor tightly coupled classes to constructor injection by hand, Spot who creates which object in a small program, Pick the right Initializr settings for a given app, Interview drill: what is Spring, what is Spring Boot, what is IoC
        • Mini project: ShopLite API skeleton: Generate shoplite-api with Spring Initializr (Java 17, Boot 4.1, Web MVC), Feature packages: product, category, customer, order and common, spring.application.name and a root GET /api endpoint returning the name and version, .gitignore, README with run steps, and the first push to GitHub
      • Dependency Injection & Beans

        • Beans and the application context: A bean is an object that Spring creates and manages, The ApplicationContext as the container: getBean by type and listing bean names, One shared instance by default: proving it with two getBean calls, Running code at startup with CommandLineRunner and ApplicationRunner, NoSuchBeanDefinitionException: asking for a bean that does not exist
        • @Component, @Service, @Repository and @Controller: @Component as the general marker that makes a class a bean, @Service, @Repository and @Controller: same mechanism, clearer meaning, @Repository's extra job: translating database exceptions, Default bean names and giving a bean a custom name, Reading 'required a bean of type ... that could not be found' and fixing the missing annotation
        • Constructor injection and why to prefer it: A single constructor needs no @Autowired; final fields make the class safe, Field and setter injection compared, and why ShopLite never uses field injection, Unit testing an injected class with plain new and a fake dependency, Circular dependency errors at startup and fixing them by redesigning, Too many constructor parameters as a sign the class does too much
        • @Configuration and @Bean: When you cannot annotate a class: library types such as Clock, A @Configuration class with @Bean methods; the bean name is the method name, Bean method parameters are injected like constructor parameters, A Clock bean so time-based code (sale ends, order dates) is testable, @Component scanning vs @Bean methods: when to pick which
        • Several implementations: @Qualifier and @Primary: A DiscountPolicy interface with festival and no-discount implementations, NoUniqueBeanDefinitionException: Spring cannot choose, @Primary for the default choice and @Qualifier to ask for a specific one, Injecting List<DiscountPolicy> and Map<String, DiscountPolicy> to use them all, Optional dependencies with ObjectProvider
        • Bean scopes and lifecycle callbacks: Singleton (default) vs prototype, and the request and session web scopes, Singletons are shared by all requests: the mutable-field bug and keeping beans stateless, The lifecycle: create, inject, initialise, use, destroy, @PostConstruct and @PreDestroy from jakarta.annotation, The prototype-inside-a-singleton trap and ObjectProvider as the fix
        • Practice: dependency injection and beans: Predict which bean gets injected in tricky setups, Fix startup errors: missing bean, two candidates, circular dependency, Convert field injection to constructor injection, Interview drill: bean scopes, @Bean vs @Component, why constructor injection
        • Mini project: ShopLite cart pricing with beans: CartPricingService in the order package with BigDecimal totals, DiscountPolicy implementations chosen with @Primary and @Qualifier, A GST TaxCalculator and a Clock bean from a @Configuration class, A startup runner that prices a sample cart, plus plain JUnit tests using new
      • How Spring Boot Works

        • Starters and dependency management: A starter is one dependency that brings a tested set of libraries, Starters ShopLite uses: webmvc, validation, jdbc, actuator and test (Boot 4's spring-boot-starter-webmvc name), The parent's managed versions: why dependencies have no version tag, Seeing what you really got with mvnw dependency:tree, Overriding a managed version with a property, and why to avoid it
        • Auto-configuration and @SpringBootApplication: @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan, Conditions: @ConditionalOnClass and @ConditionalOnMissingBean, Defining your own bean and watching Boot back off, The conditions report with --debug, and excluding an auto-configuration, 'Failed to configure a DataSource: url attribute is not specified' and what it means
        • Component scanning: Scanning starts at the main class's package and goes down, A bean in a sibling package is never found: the symptom and the fix, scanBasePackages and why moving the main class is usually better, How package by feature (com.shoplite.product, .order, ...) fits scanning, Startup cost of scanning and keeping the root package tidy
        • The embedded Tomcat server: Embedded server in the jar vs deploying a WAR to an external server, server.port and the context path, 'Port 8080 was already in use': finding and stopping the process on Windows and macOS, One thread per request: the Tomcat thread pool and virtual threads (spring.threads.virtual.enabled), Graceful shutdown so in-flight requests finish
        • Reading the startup log: Line by line: Java version, PID, active profiles, Tomcat port, context ready, 'Started in', 'No active profile set, falling back to default', APPLICATION FAILED TO START: reading the Description and Action blocks, Finding the root cause at the bottom of a long Caused by chain, Turning the banner off and making the log quieter
        • Spring Boot DevTools: Automatic restart when classes change, and why it is faster than a full start, Making it work in IntelliJ IDEA (build automatically) and VS Code, Development-only defaults DevTools changes (caching off), Why DevTools never reaches the production jar (optional dependency), When a restart is not enough: changes to pom.xml
        • Practice: how Spring Boot works: Read startup logs and failure reports, then fix the cause, Predict which beans auto-configuration creates, Fix scanning and port problems, Interview drill: what @SpringBootApplication does, how auto-configuration works
        • Mini project: ShopLite startup checks: Add the starters ShopLite needs now and check the dependency tree, A startup runner that logs the app name, port and bean count, Override an auto-configured bean and confirm it in the conditions report, Port from the command line, graceful shutdown, DevTools, and a troubleshooting section in the README
      • Building REST Controllers

        • @RestController and @RequestMapping: @RestController = @Controller + @ResponseBody, A class-level @RequestMapping("/api/products") base path, Returning an object and getting JSON back (Jackson does the conversion), Calling the endpoint with curl and reading the response, A path with no mapping: what the 404 looks like
        • @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping: Mapping list, get, create, replace, partly update and delete to methods, PUT replaces, PATCH changes some fields: designing both for a product, 405 Method Not Allowed when the method does not match, consumes and produces, and 415 Unsupported Media Type when Content-Type is wrong, Which methods are safe and idempotent, and why it matters for retries
        • @PathVariable and @RequestParam: @PathVariable for /api/products/{id}, @RequestParam for filters: required, defaultValue and Optional, Several query parameters together: ?category=3&minPrice=100&page=0&size=20, Automatic type conversion and the 400 you get for /api/products/abc, Path variable or query parameter: how to choose
        • @RequestBody: reading JSON into objects: @RequestBody turns the JSON body into a Java record, How JSON field names match record components, Unknown fields, missing fields and null values, Malformed JSON and a missing body: the 400 HttpMessageNotReadableException, Sending JSON bodies with curl on Windows and macOS (quoting differences)
        • ResponseEntity and status codes: ResponseEntity.ok, noContent and notFound, @ResponseStatus on a method as the short form, Choosing codes: 200, 201, 204, 400, 404, 409, Adding headers to a response, Optional from a service mapped to 200 or 404
        • Request and response DTOs: Why controllers never expose entities: hidden fields and accidental changes, Records as DTOs: CreateProductRequest, UpdateProductRequest, ProductResponse, Jackson rules: @JsonProperty, dates as ISO-8601, BigDecimal prices, Leaving out null fields and nesting a CategorySummary inside ProductResponse, A list response vs a page response object
        • Returning 201 Created with a Location header: Why a create returns 201 and where to find the new resource, Building the URI with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"), ResponseEntity.created(uri).body(response), Seeing the header with curl -i, How clients use the Location header
        • Testing controllers with @WebMvcTest: A slice test loads only the web layer, so it is fast, Replacing the service with @MockitoBean, MockMvcTester: performing requests and asserting status and JSON, Testing 201 with Location, 204 and 404 paths, Why slice tests beat starting the whole app for controller checks
        • Practice: REST controllers: Write endpoints from a short API description, Fix wrong status codes, mappings and DTOs, Predict the curl response for given requests, Interview drill: PUT vs PATCH, @RequestParam vs @PathVariable, @Controller vs @RestController
        • Mini project: ShopLite category endpoints: GET, POST, PUT and DELETE for /api/categories with record DTOs, 201 with Location on create, 204 on delete, 404 for unknown ids, A temporary in-memory CategoryService (replaced by MySQL in the last module), A curl script for every endpoint and @WebMvcTest tests
      • Layered Architecture in Spring

        • What belongs in each layer: Controller: HTTP in and out only, Service: business rules, coordination and later transactions, Repository: storing and loading data, nothing else, Following one request through all three layers, Dependencies point one way: controller to service to repository
        • Mapping between entities and DTOs: Entity (Product) vs DTO (ProductResponse): different jobs, different fields, Mapping in the service so entities never reach the controller, A static from() factory on the response record vs a small ProductMapper class, Mapping lists with streams, Keeping internal fields (cost price, timestamps) out of responses
        • An in-memory repository before the database: A ProductRepository interface: findById returning Optional, findAll, save, deleteById, InMemoryProductRepository with ConcurrentHashMap and AtomicLong ids, Why thread safety matters in a singleton repository, Swapping to a JDBC implementation later without touching the service, Fake repositories make fast service unit tests
        • Package by layer vs package by feature: Package by layer: controller, service, repository folders, Package by feature: product, category, customer, order, common, Package-private classes to hide a feature's internals, How features talk: OrderService uses ProductService, not ProductRepository, Why ShopLite uses package by feature as it grows
        • Common layering mistakes: Business rules inside controllers, Controllers calling repositories directly, Services that return ResponseEntity or read HttpServletRequest, Returning entities from controllers, The god service: splitting a 600-line class step by step
        • Practice: layered architecture: Place given code snippets in the right layer, Refactor a controller that does everything, Write mappers and a fake repository, Interview drill: why layers, DTO vs entity, package by feature
        • Mini project: ShopLite products, layered: The product feature: controller, service, repository interface and in-memory implementation, Product DTOs and a mapper; a product must belong to an existing category, Filtering by category and price range, Service unit tests with a fake repository and @WebMvcTest controller tests
      • Validation

        • Bean Validation annotations: Adding spring-boot-starter-validation and the jakarta.validation package, @NotNull vs @NotEmpty vs @NotBlank with the same inputs, @Size, @Min, @Max, @Positive, and @DecimalMin and @Digits for BigDecimal prices, @Email and @Pattern (a 10-digit Indian mobile number, a SKU format), Writing clear messages with the message attribute
        • @Valid on request bodies: @Valid @RequestBody runs the checks before your method, MethodArgumentNotValidException and the default 400 response, Nested objects and lists need @Valid too: order items, Constraints on record components, Forgetting @Valid: the silent bug where nothing is checked
        • Validating path and query parameters: Constraints directly on parameters: @Positive id, @Max(100) size, Built-in method validation in Spring MVC and HandlerMethodValidationException, The older @Validated-on-the-class style and ConstraintViolationException, Validating a page and size pair, Type errors (abc for a number) vs constraint errors (-5)
        • Writing a custom validator: A @Sku annotation and its ConstraintValidator, Reusing built-in constraints by composing annotations, A class-level validator for cross-field rules: sale price below price, Validation groups for create vs update, and when to use separate DTOs instead, Unit testing a validator with Validator directly
        • Validation in the service layer for business rules: Format checks at the edge, business rules in the service, Rules that need data: unique SKU, category exists, enough stock, Throwing meaningful exceptions from the service, Why these rules do not belong in annotations, Order of checks: cheap format checks first, data checks after
        • Practice: validation: Add constraints to DTOs from written requirements, Predict which requests pass and which fail, Fix validation that does not run or checks the wrong thing, Interview drill: @Valid vs @Validated, @NotNull vs @NotBlank, where business rules go
        • Mini project: ShopLite input validation: Constraints on product, category and customer request DTOs, Order requests with nested validated items, A custom @Sku validator and validated query parameters, Service rules: unique SKU, existing category, stock checks
      • Exception Handling

        • Default Spring error responses: An uncaught exception becomes a 500 and a stack trace in the log, The /error endpoint: JSON for API clients, the Whitelabel page for browsers, Default fields: timestamp, status, error, path, server.error.include-message and include-stacktrace, and why prod hides them, Why clients need one predictable error shape
        • Custom exceptions such as NotFound and Conflict: ResourceNotFoundException, ConflictException and BusinessRuleException, A small hierarchy with a ShopLite base exception, Thrown by services, never built in controllers, @ResponseStatus on an exception class and ResponseStatusException for one-offs, Good messages: what failed and which id, never internal details
        • @RestControllerAdvice and @ExceptionHandler: @ExceptionHandler inside one controller, @RestControllerAdvice for one global handler, Which handler wins: the most specific exception type, A catch-all handler that logs the error and returns a safe 500, Never swallow: log with the stack trace once, in one place
        • Validation error responses with field details: Turning MethodArgumentNotValidException into a list of field errors, HandlerMethodValidationException for parameter errors, Malformed JSON (HttpMessageNotReadableException) and wrong types (MethodArgumentTypeMismatchException), One errors array shape for every kind of bad input, Showing several field errors at once so the client fixes all of them
        • ProblemDetail and RFC 9457 errors: The standard: type, title, status, detail and instance (RFC 9457 replaced RFC 7807), Spring's ProblemDetail class and the application/problem+json content type, Extra properties: errors, timestamp and a trace id, spring.mvc.problemdetails.enabled and extending ResponseEntityExceptionHandler, ErrorResponseException for exceptions that carry their own ProblemDetail
        • Practice: exception handling: Map error cases to status codes and exceptions, Fix handlers that leak stack traces or swallow errors, Predict the response body for failing requests, Interview drill: @ControllerAdvice, ProblemDetail, checked vs unchecked in Spring
        • Mini project: ShopLite global error handling: ShopLite exceptions for not found, conflict and business rule failures, One GlobalExceptionHandler in com.shoplite.common returning ProblemDetail, Field errors for validation, safe 500 with logging, @WebMvcTest tests that check every error shape
      • Configuration, Profiles & Logging

        • application.properties vs application.yml: The same settings written both ways, YAML indentation mistakes and how they show up, Relaxed binding: max-page-size, maxPageSize and MAX_PAGE_SIZE, Where values come from and who wins: command line, environment, files, Picking one format per project
        • @Value and @ConfigurationProperties: @Value("${shoplite.low-stock-threshold:5}") with a default, A ShopLiteProperties record bound with @ConfigurationProperties("shoplite"), Registering it with @ConfigurationPropertiesScan, Validating settings with @Validated so bad config fails at startup, Why typed properties beat scattered @Value strings
        • Profiles: dev, test and prod: application-dev.properties and application-prod.properties on top of the base file, Activating a profile: spring.profiles.active, SPRING_PROFILES_ACTIVE, --spring.profiles.active, @Profile on beans: a fake notifier in dev, the real one in prod, The test profile with @ActiveProfiles, Profile groups and the default profile
        • Environment variables and secrets: ${DB_PASSWORD} placeholders and SPRING_DATASOURCE_PASSWORD style names, Setting environment variables on Windows (PowerShell) and macOS (zsh), and in IntelliJ run configs, Never commit secrets: .gitignore, a committed application.properties.example, Failing fast in prod when a secret is missing, What to do if a secret was pushed to GitHub
        • Logging with SLF4J: levels and what to log: SLF4J with Logback by default: getting a Logger, Levels TRACE to ERROR and logging.level per package, Parameterised messages with {} and logging an exception with its stack trace, What to log (order placed, id, timing) and what never to log (passwords, full card or phone data), Log files, patterns, and structured JSON logs for production
        • Health checks with Spring Boot Actuator: Adding Actuator and calling /actuator/health, Exposing only the endpoints you need, and why the rest stay hidden in prod, Health details and the database health indicator, /actuator/info with the app version and Git commit, Liveness and readiness for deployments, and a custom HealthIndicator
        • Practice: configuration, profiles and logging: Predict the final value of a property set in several places, Fix broken YAML, wrong profile names and missing secrets, Improve poor log statements, Interview drill: profiles, @Value vs @ConfigurationProperties, Actuator
        • Mini project: ShopLite configuration and profiles: A validated ShopLiteProperties record (low-stock threshold, max page size), dev and prod profiles with different logging and error details, SLF4J logging in services and secrets from environment variables, Actuator health and info exposed safely
      • API Documentation with OpenAPI

        • What OpenAPI and Swagger UI are: OpenAPI: a JSON or YAML contract that describes every endpoint, Reading a small spec: paths, operations, schemas, responses, Swagger UI: the spec as a web page you can try, Code-first vs contract-first, Who uses the docs: frontend developers, testers, other teams
        • Adding springdoc-openapi: The springdoc-openapi-starter-webmvc-ui dependency in the version that matches Boot 4, /v3/api-docs and /swagger-ui.html, An OpenAPI bean with title, version, description and contact, Limiting docs to /api/** and grouping by feature, Turning Swagger UI off in the prod profile
        • Describing endpoints, parameters and responses: @Tag and @Operation with a summary and description, @Parameter for path and query parameters, @ApiResponse for 201, 400, 404 and 409 with the ProblemDetail schema, @Schema on DTO records: descriptions and example values, Bean Validation constraints showing up in the docs automatically
        • Testing your API from Swagger UI: Try it out: filling parameters and editing the request body, Reading the response code, headers and body, The curl command Swagger UI generates, Exporting the spec and importing it into Postman as a collection, Keeping the docs true: checking them in a test
        • Practice: OpenAPI documentation: Document endpoints from their code, Fix docs that show wrong status codes or schemas, Read a spec and write the matching curl requests, Interview drill: OpenAPI vs Swagger, code-first vs contract-first
        • Mini project: ShopLite API docs: springdoc-openapi with ShopLite's title, version and contact, Every category and product endpoint documented with tags, operations and ProblemDetail errors, Example values on request and response records, Swagger UI off in prod, and a Postman collection imported from the spec
      • Spring Boot Mini Project: ShopLite REST API

        • Connecting Spring Boot to MySQL: spring-boot-starter-jdbc and mysql-connector-j, spring.datasource url, username and password from environment variables, HikariCP is auto-configured: pool size and timeouts, Communications link failure and Access denied: what they mean and how to fix them, The ShopLite schema from Section 12 loaded once with a script (Flyway takes over in Section 16)
        • From DAO classes to JdbcClient and JdbcTemplate repositories: What JdbcTemplate removes: connections, try-with-resources, SQLException handling, JdbcClient: sql(), param(), query(), list(), optional() and update(), A RowMapper that builds Product records, and the same with JdbcTemplate, Inserting and reading the generated id with a KeyHolder, DataAccessException, DuplicateKeyException to 409, and 0 rows updated to 404
        • Transactions with @Transactional: Placing an order: insert order, insert items, reduce stock in one transaction, @Transactional on the service method and rollback on runtime exceptions, Checked exceptions do not roll back by default, The self-invocation trap: calling a @Transactional method from the same class, readOnly for queries and a race-safe stock update (UPDATE ... WHERE stock >= ?)
        • Practice: Spring Boot review and interview drill: Mixed exercises across DI, controllers, validation, errors and configuration, Find and fix the bugs in a small Spring Boot feature, JdbcClient and @Transactional exercises, Interview drill: the 20 most asked Spring Boot questions
        • Project: ShopLite catalog on MySQL: Category and product repositories rewritten with JdbcClient against the ShopLite schema, In-memory repositories removed; services and controllers unchanged, Filtering and paging products in SQL, Validation and ProblemDetail errors checked against the real database
        • Project: ShopLite customers and orders: Customer endpoints with validation and duplicate-email 409, Order placement in one @Transactional service method with stock checks, Order lookup with items and totals in BigDecimal, Order status changes with business rules and ProblemDetail errors
        • Project: ShopLite REST API release: dev and prod profiles with MySQL settings from environment variables, OpenAPI docs for every endpoint and a Postman collection in the repo, Actuator health with the database check and structured logs in prod, A @SpringBootTest smoke test, a runnable jar and a complete README
    5. Spring Data JPA & Hibernate

      Map Java objects to tables, model relationships, write repository queries and avoid the common performance traps.

      • ORM, JPA & Hibernate

        • The object-relational mismatch: Recap: the Section 15 JdbcClient ProductRepository with hand-written SQL and row-to-record mapping, Four mismatches: object references vs foreign keys, collections vs rows in another table, inheritance vs flat tables, Java identity (== and equals) vs primary keys, What an ORM does: maps classes to tables, writes the SQL, tracks changed objects, What an ORM costs: hidden SQL, a learning curve and performance traps, When plain JDBC or JdbcClient is still the better tool: reports, bulk jobs, heavy SQL
        • JPA, Hibernate and Spring Data JPA: JPA (Jakarta Persistence 3.2) is a specification: annotations in jakarta.persistence and the EntityManager API, Hibernate 7 is the implementation Spring Boot 4 uses; EclipseLink is another; the old javax.persistence names are gone, Spring Data JPA on top: you write a repository interface, Spring generates the class at runtime, The full stack: controller -> service -> Spring Data repository -> EntityManager -> Hibernate -> JDBC -> HikariCP -> MySQL, Which import to use: jakarta.persistence first, org.hibernate.annotations only for Hibernate-only features
        • Adding the JPA starter and configuring MySQL: spring-boot-starter-data-jpa and mysql-connector-j in pom.xml, versions managed by Spring Boot 4.1, spring.datasource url, username and password from environment variables; HikariCP is the default pool, spring.jpa.hibernate.ddl-auto values (none, validate, update, create, create-drop) and why ShopLite uses validate against the Section 12 schema, A first entity and repository: a minimal Category @Entity, CategoryRepository extends JpaRepository, findAll() printed from a CommandLineRunner, Startup errors decoded: Communications link failure, Access denied for user, Unknown database 'shoplite', Failed to determine a suitable driver class
        • Seeing the SQL Hibernate generates: spring.jpa.show-sql vs logging.level.org.hibernate.SQL=DEBUG, and why the logger is the better choice, Readable SQL with hibernate.format_sql and bound values with logging.level.org.hibernate.orm.jdbc.bind=TRACE, Reading a generated SELECT: table aliases like c1_0 and the full column list, A statement count with hibernate.generate_statistics, Keeping SQL logging in the dev profile only (application-dev.yml)
        • Practice: ORM and JPA setup: Match each job to JPA, Hibernate or Spring Data JPA, Fix broken pom.xml and application.yml setups from their startup errors, Predict which ddl-auto value fits dev, test and production, Interview drill: ORM vs JDBC, JPA vs Hibernate
        • ShopLite: add Spring Data JPA and serve categories: A new branch in the shoplite-api repository; JPA starter and MySQL settings in application.yml with environment variables per profile, A Category entity (parent mapped later, in Relationships) and a CategoryRepository replacing the JdbcClient category repository, CategoryService keeps its contract: the controller still returns CategoryResponse records, ddl-auto=validate, SQL logging in the dev profile only, GET /categories checked with curl and the logged SQL
      • Entities & Mapping

        • @Entity, @Table, @Id and @GeneratedValue: Entity rules: @Entity, a protected no-arg constructor, a non-final class, and why a record cannot be an entity, @Table(name = "products") and Spring's default naming (unitPrice -> unit_price), @Id with @GeneratedValue(strategy = GenerationType.IDENTITY) for MySQL AUTO_INCREMENT; Integer ids for INT columns, Field access vs property access; getters without a public setter for the id, Errors: "No identifier specified for entity" and "Not a managed type" (entity outside the scanned package)
        • @Column: names, lengths, nullability and uniqueness: @Column(name, nullable, length, unique, precision, scale) and when each one matters: schema generation, validation or runtime, nullable = false is not input validation: Bean Validation on request DTOs vs constraints on entities and in MySQL, Mapping customers: full_name, a unique email and a nullable phone, @Transient fields, and insertable = false / updatable = false for columns the database fills, Schema-validation errors: "missing column [..] in table [..]" and "wrong column type encountered"
        • Enums, dates and BigDecimal fields: @Enumerated(EnumType.STRING) for OrderStatus, and how ORDINAL corrupts data when constants are reordered, java.time types: LocalDateTime for DATETIME, LocalDate for DATE, Instant for UTC moments; no @Temporal needed, BigDecimal price with precision 10 and scale 2; why double is wrong for money, Mapping BOOLEAN columns like is_active to boolean fields, An AttributeConverter for a custom type (a Pincode value stored as CHAR(6))
        • Embedded value objects with @Embeddable: Value object vs entity: no id of its own, compared by its values, A PostalAddress @Embeddable (line1, city, state, pincode) inside ShopLite's Address entity, @Embedded and @AttributeOverride to change column names or reuse one embeddable twice, Records as embeddables (supported by Hibernate 7), What happens when every embedded column is NULL
        • Auditing: created and updated timestamps: Spring Data auditing: @EnableJpaAuditing, @EntityListeners(AuditingEntityListener.class), @CreatedDate and @LastModifiedDate, Hibernate's @CreationTimestamp and @UpdateTimestamp, and which one to choose, A @MappedSuperclass for shared audit fields, Database defaults vs timestamps set by the app; storing UTC with hibernate.jdbc.time_zone, A preview of @CreatedBy with AuditorAware, filled in after Spring Security (Section 17)
        • equals and hashCode for entities: Why the default Object.equals breaks when the same row is loaded twice or detached, The HashSet bug: an id-based hashCode changes after persist and the element is "lost", Two safe designs: a natural key (sku, email) or id-based equals with a constant hashCode, Hibernate proxies: use instanceof, not getClass(), and why Lombok @Data on entities is dangerous, toString without lazy associations
        • Practice: entities and mapping: Map given CREATE TABLE statements to entities, Fix wrong mappings from their schema-validation errors, Choose STRING vs ORDINAL, BigDecimal vs double, embeddable vs entity, Interview drill: entity rules, equals/hashCode, auditing
        • ShopLite: map products, customers, addresses and orders: Customer entity with a unique email, a nullable phone and createdAt from auditing, Product entity: unique sku, BigDecimal price, stock, active flag; category_id kept as a plain column only until Relationships, Address entity with an embedded PostalAddress and isDefault; customer_id as a plain column until Relationships, Order entity with an OrderStatus enum stored as STRING and orderedAt; the app boots with ddl-auto=validate against the Section 12 schema
      • Repositories & Queries

        • JpaRepository and the built-in CRUD methods: The repository hierarchy: Repository -> CrudRepository -> ListCrudRepository -> JpaRepository, and the proxy Spring creates, save, saveAll, findById returning Optional, findAll, existsById, count and deleteById, each with its logged SQL, getReferenceById vs findById: a proxy without a SELECT, Turning Optional.empty() into a ProductNotFoundException and a 404 ProblemDetail, Repositories are used by services only; controllers get DTOs
        • Derived query methods from method names: findBySku, findByEmailIgnoreCase, existsByEmail, countByActiveTrue and the SQL each produces, Keywords: And, Or, Between, LessThan, GreaterThanEqual, Containing, StartingWith, In, IsNull, OrderBy, findFirst/findTop and the Limit parameter; returning Optional, List or Stream, Typos fail at startup: "No property 'title' found for type 'Product'", When a method name gets too long: switch to @Query
        • @Query with JPQL: JPQL uses entity and field names, not table and column names, Named parameters (:name with @Param) and positional ?1, LIKE with lower() and concat(), IN lists, and aggregates (count, sum) returning long or BigDecimal, JPQL is checked at startup: "Could not resolve attribute" and unknown entity errors, A ShopLite low-stock query
        • Native SQL queries: @Query(nativeQuery = true) and @NativeQuery for MySQL-only features, such as a window-function sales report, Mapping native results to entities or to interface projections, Parameters are still bound safely; never build SQL by joining strings (SQL injection recap), Trade-offs: no startup check, tied to MySQL and to column names
        • Projections and DTO queries: Interface projections (ProductSummary with getName and getPrice) and the narrower SELECT they produce, Record projections with a JPQL constructor expression: select new com.shoplite.product.ProductSummary(...), Dynamic projections with a Class<T> parameter, Closed vs open projections: @Value expressions load the whole entity, Returning records from the repository straight to the response
        • @Modifying update and delete queries: @Modifying @Query("update Product p set p.active = false where p.category.id = :id") returning the row count, A transaction is required: TransactionRequiredException and how @Transactional fixes it, Bulk queries bypass loaded objects: clearAutomatically and flushAutomatically, Derived deleteBy loads and deletes rows one by one; a bulk delete query does it in one statement, Bulk update vs load-and-change: a 10% price rise for one category
        • Practice: repositories and queries: Write the same query as a derived method, JPQL and native SQL, Predict the SQL a repository method sends, Fix broken method names, JPQL and missing @Modifying, Interview drill: projections, getReferenceById, bulk updates
        • ShopLite: product and customer repositories on Spring Data JPA: ProductRepository and CustomerRepository replace the JdbcClient repositories; service contracts stay the same, findBySku and existsByEmail for duplicate checks returning 409 ProblemDetail, The product list through a ProductSummary projection, and a JPQL low-stock query, A @Modifying deactivate-by-category query; @DataJpaTest slice tests against MySQL
      • Relationships

        • @ManyToOne and @OneToMany: Product -> Category as @ManyToOne with @JoinColumn(name = "category_id"), Category -> products as @OneToMany(mappedBy = "category"), and when you do not need the collection at all, Default fetch types: @ManyToOne is EAGER, so always set fetch = FetchType.LAZY, A self-reference: Category parent and children from categories.parent_id, Collections: List vs Set, always initialised to an empty collection
        • Owning side, mappedBy and join columns: The owning side holds the foreign key and is the only side Hibernate reads when saving, The bug: adding to the mappedBy list only, so the foreign key is never written, @JoinColumn name and nullable; a unidirectional @OneToMany without mappedBy creates a join table and extra SQL, Errors: "mappedBy reference an unknown target entity property" and "Column 'category_id' cannot be null"
        • Keeping both sides in sync with helper methods: addItem and removeItem helpers on Order that set both sides, An unmodifiable getter so callers cannot bypass the helpers, Stale in-memory data inside one transaction when the helpers are missing, StackOverflowError from toString or Jackson on bidirectional links, and why entities are never serialized directly
        • @ManyToMany and when to use a join entity instead: @ManyToMany with @JoinTable on a teaching example: students and courses, Why link tables grow extra columns: ShopLite's order_items has quantity and unit_price, Modelling OrderItem as an entity with two @ManyToOne links, The unique (order_id, product_id) constraint; a surrogate id vs @EmbeddedId composite keys, Set vs List for @ManyToMany: the delete-all-and-reinsert behaviour of bags
        • @OneToOne: A foreign-key one-to-one with a unique column, on a teaching example: a customer and a wallet, @MapsId to share the primary key, The inverse side of @OneToOne cannot be lazy reliably, and what to do about it, When a one-to-one should just be extra columns or an @Embeddable
        • Cascade types and orphanRemoval: CascadeType PERSIST, MERGE, REMOVE and ALL: Order -> items is right, Product -> Category never, orphanRemoval = true: removing an item from the list deletes its row, JPA cascade REMOVE vs ON DELETE CASCADE in MySQL, TransientPropertyValueException: "object references an unsaved transient instance", Cascade REMOVE on @ManyToMany deleting shared rows
        • Practice: relationships: Map a given schema's foreign keys to relationships, Fix missing mappedBy, wrong owning side and wrong cascades, Predict the SQL for saving a parent with children, Interview drill: owning side, join entity vs @ManyToMany, cascade vs orphanRemoval
        • ShopLite: connect the entities: Product.category and Category.parent as lazy @ManyToOne links, replacing the plain id columns, Customer and addresses with orphanRemoval for the address book, Order with customer, delivery address and items; OrderItem as the join entity with quantity and unitPrice, Helper methods and cascade on Order; GET /categories as a tree and GET /orders/{id} built as DTOs
      • The Persistence Context & Entity Lifecycle

        • Transient, managed, detached and removed: The persistence context as a first-level cache: findById twice gives one SELECT and the same object, The four states with a diagram, and the calls that move an entity between them (persist, find, detach, remove, commit), One persistence context per transaction in Spring; injecting EntityManager, Checking the state with em.contains()
        • Dirty checking: updates without save(): Change a managed entity inside @Transactional and an UPDATE is sent at commit, How it works: Hibernate compares each entity with a snapshot taken at load time, Calling save() on a managed entity is redundant, Changes to detached objects or outside a transaction are silently lost, Accidental updates from setters in mappers, and how readOnly transactions prevent them
        • Flush: when SQL is actually sent: Write-behind: INSERT and UPDATE wait until flush, Flush triggers: commit, a query that touches the changed tables (FlushModeType.AUTO), explicit flush(), Constraint errors appear at flush or commit, not at save(): a duplicate email and DataIntegrityViolationException, IDENTITY ids force an immediate INSERT on persist, and why that disables JDBC insert batching
        • save vs saveAndFlush, persist vs merge: SimpleJpaRepository.save: persist when the entity is new, merge otherwise; how "new" is decided (null id, @Version, Persistable), merge returns a different managed copy: always use the returned object, saveAndFlush to get constraint errors immediately, Hibernate 7 removed Session.save, update and saveOrUpdate: use persist and merge, The update-from-DTO pattern: load, change, let dirty checking write
        • LazyInitializationException and why it happens: Lazy proxies and collections need an open persistence context, Reproducing "could not initialize proxy - no Session" after a service returns an entity, Right fixes: map to a DTO inside the transaction, fetch what you need with a fetch join, Wrong fixes: EAGER everywhere, open-in-view, hibernate.enable_lazy_load_no_trans
        • Practice: persistence context and lifecycle: Trace entity states through a service method, Predict the SQL and its timing for a transaction, Fix lost updates, merge misuse and LazyInitializationException, Interview drill: dirty checking, flush, persist vs merge
        • ShopLite: updates with dirty checking: PATCH /products/{id} for price and stock: load, change, commit, no save(), PUT /customers/{id} with a duplicate-email check and saveAndFlush returning 409, The order details endpoint maps to DTOs inside the service, so no LazyInitializationException, An integration test that checks the logged UPDATE and its columns
      • Transactions in Spring

        • @Transactional on service methods: ACID recap from Section 13 and how Spring wraps a service method in a proxy that begins and commits, @Transactional on the service class or method; never on controllers; the default transactions in repository methods, One business operation = one transaction: a ShopLite order-placement skeleton, The auto-configured JpaTransactionManager and logging transactions (org.springframework.orm.jpa.JpaTransactionManager=DEBUG)
        • Rollback rules for checked and unchecked exceptions: Default: roll back on RuntimeException and Error, commit on checked exceptions, rollbackFor and noRollbackFor, Catching an exception inside: UnexpectedRollbackException "Transaction silently rolled back because it has been marked as rollback-only", Designing ShopLite exceptions (OutOfStockException) as unchecked, A test that checks stock is unchanged after a failure
        • Read-only transactions: @Transactional(readOnly = true): Hibernate skips snapshots and flush, and the driver gets a read-only hint, Class-level readOnly with method-level overrides for writes, What readOnly does not promise: it is not a security check, Isolation levels in one view: MySQL's REPEATABLE READ default and when to change it, The idea of routing read-only transactions to a replica
        • Propagation basics: REQUIRED and REQUIRES_NEW: REQUIRED joins the caller's transaction, so an inner failure rolls back everything, REQUIRES_NEW suspends the outer transaction: an audit record that must survive a rollback, REQUIRES_NEW holds two connections: pool exhaustion under load, The other options in one line each: MANDATORY, SUPPORTS, NOT_SUPPORTED, NEVER, NESTED
        • Self-invocation and other reasons @Transactional is ignored: Self-invocation: this.method() bypasses the proxy, shown with the transaction log, private and final methods, objects created with new, classes that are not Spring beans, Fixes: move the method to another bean, restructure, or use TransactionTemplate, Checking at runtime with TransactionSynchronizationManager.isActualTransactionActive()
        • Optimistic locking with @Version vs pessimistic locks: The lost update: two admins edit the same product price, @Version: the version check in the UPDATE, ObjectOptimisticLockingFailureException mapped to 409 ProblemDetail, Pessimistic locks: @Lock(LockModeType.PESSIMISTIC_WRITE) sends SELECT ... FOR UPDATE; lock timeouts, An atomic alternative for stock: UPDATE ... SET stock = stock - :qty WHERE stock >= :qty, Choosing: optimistic for rare conflicts, pessimistic or atomic updates for hot rows; deadlocks and locking in a fixed order
        • Practice: transactions in Spring: Predict commit or rollback for given service code, Fix self-invocation, swallowed exceptions and checked-exception commits, Pick a locking strategy for given concurrent scenarios, Interview drill: propagation, readOnly, optimistic vs pessimistic
        • ShopLite: cancel an order safely: POST /orders/{id}/cancel: only PLACED orders, stock restored for every item, all in one @Transactional service method, OrderCannotBeCancelledException (unchecked) mapped to 409 ProblemDetail, OrderService read methods marked readOnly, An integration test proving a failure halfway leaves stock and status unchanged
      • Pagination, Sorting & Searching

        • Pageable, Page and Slice: PageRequest.of(page, size): pages start at 0, LIMIT and OFFSET in the SQL, Page<T>: content, totalElements, totalPages and the extra COUNT query, Slice<T>: hasNext() without a COUNT; List with a Pageable, A custom countQuery for @Query pages, Fetch join + paging warning: "HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory"
        • Sorting by one or more fields: Sort.by("price").descending().and(Sort.by("name")), Type-safe sorting with Sort.sort(Product.class).by(Product::getPrice), Sorting inside a Pageable, and a unique tiebreaker (id) for stable pages, Untrusted sort fields: "No property 'cost' found for type 'Product'" and a whitelist
        • Exposing page and sort in REST endpoints: A Pageable controller parameter: ?page=0&size=20&sort=price,desc, Limits: @PageableDefault and spring.data.web.pageable.max-page-size, A stable JSON shape: @EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO) or your own PageResponse record, instead of serializing PageImpl, Mapping Page<Product> to Page<ProductResponse> with page.map, Real curl requests and responses
        • Optional filters with Specifications: Why findBy methods explode with optional filters, JpaSpecificationExecutor and Specification<Customer> lambdas with CriteriaBuilder, Composing filters with and(), skipping null filters, Joins in a Specification (customers by address city) and duplicate rows, Query by Example as a lighter alternative
        • Keyset pagination for large tables: Why OFFSET gets slow: MySQL reads and throws away every skipped row, The keyset idea: WHERE (ordered_at, order_id) < (?, ?) ORDER BY ... LIMIT ?, Spring Data scrolling: ScrollPosition.keyset() and Window<T>, Trade-offs: no jumping to page N, needs a unique sort key and a matching index
        • Practice: pagination, sorting and searching: Write paged and sorted queries for given screens, Build Specifications from optional filters, Fix in-memory paging, unstable sorts and unbounded page sizes, Interview drill: Page vs Slice, OFFSET vs keyset
        • ShopLite: paged customers and order lists: GET /customers with page, size and whitelisted sort fields, and a maximum page size, Admin customer search with optional name, email and city filters as Specifications, GET /customers/{id}/orders paged, newest first, A PageResponse record and real curl output in the README
      • Performance Traps

        • Lazy vs eager fetching: Default fetch types per association, and the extra SQL an EAGER @ManyToOne sends, EAGER cannot be turned off per query, and with JPQL it still loads with extra SELECTs, Proxies: getId() on a lazy link without a SELECT, The rule: map everything LAZY, fetch per use case
        • The N+1 query problem: Reproducing it: list orders, then call order.getCustomer().getFullName() -> 1 + N SELECTs, Spotting it in the SQL log and in Hibernate statistics, Hidden N+1: Jackson serialization, toString and mappers, The cost: timing 20 rows vs 2000 rows
        • Fixes: JOIN FETCH, @EntityGraph and batch fetching: JOIN FETCH in JPQL; DISTINCT is no longer needed since Hibernate 6, @EntityGraph(attributePaths = ...) on repository methods, @BatchSize and hibernate.default_batch_fetch_size: IN queries instead of N SELECTs, Fetching two collections: MultipleBagFetchException and its fixes (Set or two queries), Fetch join with paging: fetch the page of ids first, then the entities
        • Returning DTOs instead of entities: Read endpoints do not need managed entities: one constructor-expression query with joins, Fewer columns and no dirty-checking snapshots, Entity graph vs DTO query: when each one wins, Entities stay inside the service layer; controllers only see records
        • Open Session in View and why to turn it off: What spring.jpa.open-in-view=true does and the startup warning it prints, How it hides LazyInitializationException and moves N+1 queries into the web layer, It holds a database connection for the whole request: pool exhaustion under load, Turning it off: what breaks and how DTO mapping in services fixes it
        • Counting queries in tests and logs: Hibernate Statistics in a test: getPrepareStatementCount() before and after a call, A test that fails when the query count grows, to stop regressions, A proxy DataSource logger (datasource-proxy) for per-request SQL counts, MySQL's slow query log and EXPLAIN on the SQL Hibernate generated, Indexes for foreign-key and sort columns
        • Practice: JPA performance traps: Count the queries given code will send, Fix N+1, eager mappings and in-memory paging, Choose fetch join, entity graph, batch fetching or a DTO query, Interview drill: N+1, Open Session in View, lazy vs eager
        • ShopLite: a fast product listing: Measure the N+1 in the product list with category names, Fix it with an @EntityGraph or a DTO query, locked in by a query-count test, The category tree in two queries with batch fetching, spring.jpa.open-in-view=false in every profile, with the README noting before/after query counts
      • Schema Migrations with Flyway

        • Why ddl-auto=update is unsafe: What update does and does not do: no drops, no renames, no data moves, different results per environment, Renaming a field: a new empty column appears and the data stays behind, create and create-drop only for throwaway tests; validate everywhere else, Migrations as versioned SQL, reviewed in Git like code
        • Adding Flyway and writing V1: Spring Boot 4: spring-boot-starter-flyway plus flyway-mysql, src/main/resources/db/migration and the naming rule V1__create_schema.sql, The flyway_schema_history table: version, checksum, success, An existing database: baseline-on-migrate and baseline-version, Errors: "Found non-empty schema(s) ... but no schema history table" and "Unsupported Database: MySQL" (missing flyway-mysql)
        • Changing a live schema with new migrations: Never edit an applied migration: "Migration checksum mismatch for migration version 1" and flyway repair, V2 adds a column with a default; V3 adds an index, Expand and contract: renaming a column without downtime, MySQL DDL is not transactional: recovering from a half-applied migration, Team branches that pick the same version number
        • Seed data and repeatable migrations: Reference data in versioned migrations vs dev-only sample data, spring.flyway.locations per profile: classpath:db/migration plus classpath:db/dev-data, R__ repeatable migrations (for example a view) rerun when their checksum changes, Flyway callbacks such as afterMigrate, and Java-based migrations in one line
        • Validating entities against the schema: Startup order: Flyway migrates, then Hibernate validates with ddl-auto=validate, Reading validation errors: missing table, missing column, wrong column type (DECIMAL vs DOUBLE, INT vs BIGINT), An integration test that boots against a fresh MySQL database and runs every migration, spring.flyway.clean-disabled and why clean must never run in production
        • Practice: Flyway migrations: Write the next migration for given schema changes, Fix checksum mismatches, wrong file names and failed migrations, Plan a column rename with expand and contract, Interview drill: Flyway vs ddl-auto, versioned vs repeatable
        • ShopLite: Flyway owns the schema: V1 from the Section 12 CREATE script, and baselining the existing dev database, Section 12 seed data in a dev-only location, V2 adds an index on orders(customer_id, ordered_at) for order history, ddl-auto=validate, a fresh-database migration test and README steps to set up the database
      • JPA Mini Project: ShopLite on JPA

        • ShopLite on JPA: finish the data layer: Products, categories, customers with addresses, orders and order items all on Spring Data JPA; the JdbcClient code removed, Flyway scripts from the original Section 12 schema run on a fresh database and ddl-auto=validate passes, Entities stay inside services; every controller returns records, @DataJpaTest per repository plus one full-context smoke test
        • ShopLite: paged and filtered product search: GET /products?q=&categoryId=&minPrice=&maxPrice=&inStock=&page=&size=&sort=, Specifications composed from the optional filters, Whitelisted sort fields, a maximum page size and a PageResponse, An index added through a new Flyway migration, checked with EXPLAIN
        • ShopLite: place orders with stock locking: POST /orders in one @Transactional method: check customer and address, lock products with PESSIMISTIC_WRITE in id order, check and reduce stock, save the Order with its items, unit_price copied from the current price; totals in BigDecimal, OutOfStockException mapped to 409 and a test proving full rollback, A concurrency test: two threads buy the last unit and exactly one succeeds
        • Practice: Spring Data JPA interview drill: Predict the SQL Hibernate sends for given code, Bug hunts: missing @Transactional, wrong owning side, N+1, self-invocation, Design questions: modelling orders, money and soft delete, Mixed review across the whole section
        • ShopLite: fix N+1 in order history: GET /customers/{id}/orders with items and product names: measure the 1 + N + N*M queries, Fix it with a paged ids query followed by a fetch join, avoiding in-memory paging, A query-count test that locks the result at a fixed number, open-in-view off, and a README with before/after query counts and timings
    6. Spring Security & Authentication

      Protect your APIs: password hashing, sign-in with JWT, roles and permissions, and the common security mistakes to avoid.

      • Security Basics

        • Authentication vs authorisation: Authentication: proving who you are (password, token, one-time code), Authorisation: deciding what you may do once you are known, Real examples: an airport (passport check vs boarding pass) and a shop API (signed in vs admin), Identity, credentials, principal and permissions: the words you will meet in every framework, Where each check happens in a request: who is calling first, then is this allowed, 401 Unauthorized means not authenticated, 403 Forbidden means not allowed (the confusing names explained)
        • Common attacks: stolen passwords, injection, broken access control: Stolen and reused passwords: credential stuffing, brute force and leaked databases, Injection: SQL injection step by step with a login query, and why parameterised queries stop it, Broken access control: changing an id in the URL to read someone else's order, Cross-site scripting (XSS) and why untrusted text must never run as code in a browser, Cross-site request forgery (CSRF) in one picture: a forged request that rides on a cookie, Thinking like an attacker: list the inputs, then ask what happens if each one is hostile
        • Hashing vs encryption vs encoding: Encoding (Base64, URL encoding): changes the format, anyone can reverse it, gives no secrecy, Encryption: reversible with a key; symmetric (one shared key) vs asymmetric (public and private key), Hashing: a one-way fingerprint; same input gives the same hash, a tiny change gives a totally different hash, Why passwords are hashed, never encrypted: salts, rainbow tables, and slow hashes (BCrypt, Argon2) vs fast ones (SHA-256, MD5), Signatures and HMAC: proving data was not changed, the idea behind signed tokens, Choosing the right tool: a table of real cases (passwords, card numbers, tokens, URLs)
        • HTTPS and why tokens need it: What anyone on the network can see over plain HTTP: headers, cookies, passwords and tokens, What TLS adds: encryption, integrity and server identity with certificates, The handshake in plain words and what the padlock in the browser really means, Bearer tokens: whoever holds the token is you, so a leaked token is a stolen account, HTTPS in practice: TLS at a load balancer, HSTS, and why plain HTTP on localhost is for development only, Inspecting a request with curl -v: the TLS handshake and the headers
        • The OWASP Top 10 at a glance: What OWASP is and why the Top 10 list is used in code reviews and interviews, Broken access control (now including SSRF), security misconfiguration and software supply chain failures with one example each, Cryptographic failures, injection and insecure design, Authentication failures, software or data integrity failures, logging and alerting failures, and mishandling of exceptional conditions, Mapping each risk to the defence that stops it (and the module of this section that builds it), A short security checklist for any backend you build
        • Practice: security basics: Classify scenarios as authentication or authorisation, 401 or 403, Pick hashing, encryption or encoding for real data, Find the vulnerability in short request and query descriptions, Interview drill: explain a password leak, SQL injection and HTTPS in two minutes each
        • Mini project: ShopLite threat model: List ShopLite's users (guest, customer, admin), data and endpoints, For each endpoint decide who may call it and what they may see, Identify the risks: password storage, order access by id, admin actions, tokens in transit, Write SECURITY.md: an access table and the defence planned for each risk (built in the next modules)
      • How Spring Security Works

        • Adding the starter and the default login: Adding spring-boot-starter-security to the shoplite-api pom.xml, What happens at once: every endpoint returns 401, and the generated password in the startup log, Calling the API with curl -u user:<password> and seeing the default login page in a browser, A development user with spring.security.user.name and password (and why this is not for production), Spring Security 7 with Spring Boot 4, and spotting outdated tutorials (WebSecurityConfigurerAdapter, antMatchers, and())
        • The security filter chain: Servlet filters recap: code that runs before the controller, DelegatingFilterProxy and FilterChainProxy: how Spring plugs its filters into the server, The important filters in order: CORS, CSRF, authentication filters, ExceptionTranslationFilter, AuthorizationFilter, Following one request through the chain with logging.level.org.springframework.security=TRACE, The authentication flow: AuthenticationManager, AuthenticationProvider and the Authentication object
        • SecurityFilterChain configuration: A @Configuration class with a SecurityFilterChain @Bean taking HttpSecurity, The lambda DSL: authorizeHttpRequests, httpBasic, formLogin, csrf, sessionManagement, anyRequest().authenticated() and what defining your own chain turns off, Placing the class in com.shoplite.common.security and keeping all rules in one place, Startup failures from wrong configuration and how to read them
        • SecurityContext and the current user: SecurityContextHolder, SecurityContext and Authentication: who is calling right now, Principal, credentials and authorities inside an Authentication, Getting the current user in a controller with @AuthenticationPrincipal or an Authentication parameter, Why services receive the user id as a parameter instead of reading the context everywhere, Thread-local storage: the context belongs to the request thread
        • Permitting public endpoints: permitAll for GET product and category endpoints, /actuator/health and the Swagger UI paths, Matching by HTTP method and path: requestMatchers(HttpMethod.GET, "/api/products/**"), Rule order matters: specific rules first, anyRequest last, Why /error must be permitted to see real error responses, Testing public and protected endpoints with curl and with @WebMvcTest + spring-security-test
        • Practice: how Spring Security works: Predict the response (200, 401, 403) for requests against a given configuration, Fix outdated configuration code to the Spring Security 7 DSL, Order request rules correctly, Interview drill: explain the filter chain and the SecurityContext
        • Mini project: add Spring Security to ShopLite: Add the starter and a SecurityConfig in com.shoplite.common.security, Public catalogue, health and API docs; everything else requires sign-in, A temporary in-memory development user (replaced by database users in the next module), Slice tests that prove which endpoints are public and which return 401
      • Users & Password Storage

        • User entity and roles table: Designing app_user and user_role tables (unique email, password_hash, enabled, created_at) linked to the customer table, A Flyway migration that adds the tables to the ShopLite schema, The User JPA entity with an enum Role (CUSTOMER, ADMIN) mapped with @ElementCollection, A new com.shoplite.user feature package: entity, repository, service, Why the password column holds a hash and never appears in any DTO
        • UserDetails and UserDetailsService: What Spring Security needs from a user: username, password hash, authorities, enabled flag, Adapting the User entity to UserDetails (a separate adapter class, not the entity itself), Implementing UserDetailsService.loadUserByUsername with the repository, UsernameNotFoundException and why login errors must not reveal whether the email exists, How DaoAuthenticationProvider uses the UserDetailsService and PasswordEncoder together
        • PasswordEncoder and BCrypt: The PasswordEncoder interface: encode and matches, BCryptPasswordEncoder: reading a hash ($2a$10$, cost, salt, hash) and why two encodes of one password differ, Choosing the cost factor and measuring how long one hash takes, DelegatingPasswordEncoder and the {bcrypt} prefix for changing algorithms later; Argon2 as an alternative, BCrypt's 72-byte input limit and what it means for very long passwords
        • Sign-up endpoint with validation: POST /api/auth/register with a SignUpRequest record and Bean Validation (@Email, @Size, @NotBlank), A password policy: minimum length, and why length beats complexity rules, UserService.register: hash the password, assign CUSTOMER, create the customer row, save in one transaction, Returning 201 Created with a UserResponse that never includes the password, Normalising emails (trim, lower case) before saving and looking up
        • Handling duplicate emails: Checking existsByEmail first, and why it is not enough on its own (two requests at once), The unique constraint as the real guard, and catching DataIntegrityViolationException, A DuplicateEmailException mapped to a 409 Conflict ProblemDetail in the global handler, Account enumeration: what the error message reveals, and the trade-off for sign-up, Testing the duplicate case with @DataJpaTest and a controller test
        • Practice: users and password storage: Read BCrypt hashes and explain each part, Fix code that stores, logs or returns plain passwords, Write UserDetailsService and sign-up code from a spec, Interview drill: how should passwords be stored, and why
        • Mini project: ShopLite user accounts: Flyway migration for users and roles, plus a seeded admin with a BCrypt hash, User feature package with a database-backed UserDetailsService, POST /api/auth/register with validation and 409 for duplicates, Temporary HTTP Basic sign-in against database users, with tests
      • HTTP Basic & Sessions

        • HTTP Basic authentication: The Authorization: Basic header is Base64 of email:password (decode one by hand), httpBasic(Customizer.withDefaults()) and calling the API with curl -u, The WWW-Authenticate header on a 401 and the browser pop-up it triggers, Weaknesses: the password travels on every request, no logout, no expiry, Where Basic is still fine: internal tools and service-to-service calls over HTTPS
        • Form login and session cookies: formLogin: the login page, POST /login and the redirect after success, The JSESSIONID cookie and the server-side HttpSession that holds the SecurityContext, Cookie flags: HttpOnly, Secure and SameSite, Logout, session fixation protection and session timeout, Why sessions are harder to scale across several servers (sticky sessions, shared session stores)
        • CSRF and when it matters: The CSRF attack step by step: a hidden form on another site using your session cookie, How Spring's CSRF token works, and why POST requests fail with 403 when it is missing, SameSite cookies as an extra defence, When disabling CSRF is safe: stateless APIs that use the Authorization header, not cookies, The rule: if the browser sends credentials automatically, you need CSRF protection
        • Why stateless APIs prefer tokens: Stateful (session) vs stateless (token) authentication side by side, SessionCreationPolicy.STATELESS and what it changes, Tokens for mobile apps, single-page apps and many servers behind a load balancer, The cost of tokens: revocation is hard, so lifetimes must be short, Comparing Basic, sessions and tokens in one table
        • Practice: HTTP Basic, sessions and CSRF: Decode Basic headers and spot the leak, Fix cookie flags and CSRF settings in given configurations, Pick Basic, sessions or tokens for described apps, Interview drill: sessions vs tokens, and CSRF
        • Mini project: session login for an admin console: A small separate Spring Boot app (shoplite-admin-console) with form login against the ShopLite users table, Session cookies with safe flags, logout and session timeout, CSRF protection kept on and shown blocking a forged request, README comparing this with the stateless ShopLite API built next
      • JWT Authentication

        • JWT structure: header, payload, signature: Three Base64URL parts separated by dots: decoding a real token by hand, Standard claims (sub, iat, exp, iss) and custom claims such as roles, The signature: HS256 (shared secret) vs RS256 (private and public key), Signed is not encrypted: never put passwords or personal data in the payload, The alg none attack, and why the server must fix the expected algorithm
        • Login endpoint that returns a token: Adding spring-boot-starter-oauth2-resource-server and a JwtEncoder bean (NimbusJwtEncoder with a secret key), POST /api/auth/login: the AuthenticationManager checks email and password, A TokenService that builds a JwtClaimsSet (subject, issuer, issuedAt, expiresAt, roles), Returning a TokenResponse record (accessToken, tokenType, expiresIn), Bad credentials: one generic 401 message for a wrong email or a wrong password
        • Validating the token on each request: oauth2ResourceServer(jwt) and BearerTokenAuthenticationFilter: the filter that reads Authorization: Bearer, The JwtDecoder bean (NimbusJwtDecoder) with the same key and a fixed algorithm, Turning the roles claim into authorities with a JwtAuthenticationConverter, Stateless sessions and CSRF off for this API, with the reason written in the code, What a hand-written OncePerRequestFilter would have to do, and why the built-in filter is safer
        • Expiry, clock skew and signing keys from configuration: Short access-token lifetimes (for example 15 minutes) and the exp check, Clock skew: allowing a small difference between servers with JwtTimestampValidator, Validating the issuer and adding custom validators, A @ConfigurationProperties record for secret, issuer and lifetime, with the secret from an environment variable, Key length rules for HS256, failing at startup on a missing or weak key, and rotating keys
        • Refresh tokens and logout (the trade-offs): Why a stateless token cannot simply be deleted on logout, Refresh tokens: long-lived, stored as a hash in a refresh_token table, exchanged for new access tokens, Refresh token rotation and detecting reuse of an old token, Logout by revoking the refresh token, and when a deny-list for access tokens is worth it, Choosing a design: short tokens only, refresh tokens, or back to sessions
        • Where clients should store tokens: localStorage and XSS: any script on the page can read the token, HttpOnly cookies: safe from scripts, but CSRF protection is needed again, In-memory access token plus HttpOnly refresh cookie: the common compromise, Mobile apps: the platform's secure storage (Keychain, Keystore), Sending the token: the Authorization header, never the URL
        • Practice: JWT authentication: Decode tokens and spot dangerous claims, Fix broken JWT configuration (wrong key, missing expiry, CSRF and session settings), Trace a login and an authenticated request with curl, Interview drill: JWT vs sessions, refresh tokens and logout
        • Mini project: JWT login for ShopLite: Replace HTTP Basic with stateless JWT: login endpoint, encoder and decoder, Token settings from configuration, secret from an environment variable, Refresh endpoint with rotation, and logout that revokes the refresh token, Tests for login, expired token, bad signature and missing token
      • Roles & Permissions

        • Roles vs authorities: GrantedAuthority as a plain string; a role is an authority with the ROLE_ prefix, hasRole("ADMIN") vs hasAuthority("ROLE_ADMIN") and the double-prefix mistake, Fine-grained authorities (product:write, order:read) vs coarse roles, Role hierarchy: letting ADMIN do everything CUSTOMER can with RoleHierarchy, Where ShopLite's roles come from: database to token claim to authorities
        • URL rules with requestMatchers: requestMatchers with method and path patterns for products, categories and orders, hasRole, hasAnyRole, authenticated and permitAll side by side, Ordering rules and a deny-by-default final rule, Path pattern pitfalls: trailing slashes, ** vs *, and forgetting a new endpoint, Testing URL rules with @WithMockUser and the jwt() request post-processor
        • Method security with @PreAuthorize: @EnableMethodSecurity and @PreAuthorize("hasRole('ADMIN')") on service methods, SpEL expressions: authentication, method parameters (#id) and bean calls, @PostAuthorize, and when checking the return value makes sense, URL rules vs method rules: defence in depth, and the self-invocation proxy trap, Testing method security with a service-level test
        • Owner checks: a customer sees only their own orders: The bug: GET /api/orders/{id} returns any order to any signed-in customer, Fix 1: query by owner (findByIdAndCustomerId) and return 404 for other people's orders, Fix 2: an authorisation check in the service using the current user id from the token, Admins see every order: combining owner and role rules, /api/me endpoints (/api/me/orders) so the client never sends its own customer id
        • 401 vs 403 and custom error responses: Where each error comes from: AuthenticationEntryPoint (401) and AccessDeniedHandler (403), Why @RestControllerAdvice does not see errors raised in the filter chain, Writing ProblemDetail JSON for 401 and 403 that matches the rest of the API, The WWW-Authenticate: Bearer header with error details for invalid or expired tokens, Not leaking details: the same message for unknown users and wrong passwords, no stack traces
        • Practice: roles and permissions: Write access rules from a permission table, Find and fix missing owner checks, Predict 401, 403 or 404 for requests from different users, Interview drill: roles vs authorities, @PreAuthorize and IDOR
        • Mini project: ShopLite roles and ownership: Admin-only product, category and stock changes with URL rules and @PreAuthorize, Customers read and create only their own orders through /api/me/orders, ProblemDetail 401 and 403 from a custom entry point and access-denied handler, A test matrix: guest, customer, other customer and admin against each endpoint
      • CORS & Browser Clients

        • Why the browser blocks cross-origin calls: What an origin is: scheme, host and port (localhost:3000 vs localhost:8080), The same-origin policy and what it protects users from, CORS is enforced by the browser, not the server: why curl and Postman always work, Reading the CORS error in the browser console, Access-Control-Allow-Origin and the other CORS response headers
        • Preflight requests: Simple requests vs requests that need a preflight, The OPTIONS request: Access-Control-Request-Method and Access-Control-Request-Headers, Allow-Methods, Allow-Headers and Max-Age in the response, Why an Authorization header or a JSON body always triggers a preflight, Simulating a preflight with curl -X OPTIONS and an Origin header
        • Configuring CORS in Spring Security: http.cors(Customizer.withDefaults()) with a CorsConfigurationSource bean, Allowed origins from configuration per profile (dev: localhost:3000, prod: the real domain), Allowed methods, headers, exposed headers and allowCredentials, Why CORS must run inside the security chain so preflights are not rejected with 401, A tiny HTML page calling the API with fetch to see CORS work end to end
        • Common CORS mistakes: Allowing * with credentials, and why the browser refuses it, Reflecting any Origin back: turning CORS into a hole, @CrossOrigin and the security chain configured differently, Preflight blocked by security, missing exposed headers, and trailing-slash origin typos, CORS does not protect the server: it does not stop curl or attackers
        • Practice: CORS: Same origin or cross origin? Classify URL pairs, Predict preflights and the headers needed, Fix broken CORS configurations from browser error messages, Interview drill: the same-origin policy and CORS
        • Mini project: a browser client for ShopLite: A small static HTML and JavaScript page served from another origin, Log in, keep the access token in memory and list the customer's orders, CORS configured per profile in the ShopLite API, Preflight and error handling checked in the browser developer tools
      • Common Security Mistakes

        • Secrets in code and Git history: How secrets leak: hard-coded keys, committed application.properties, screenshots and logs, Environment variables, profile files kept out of Git and a committed .example file, A leaked secret stays in Git history: rotate it first, then clean the history, Scanning for secrets with gitleaks and GitHub secret scanning, Different secrets per environment, and failing at startup when one is missing
        • Leaking data through entities and error messages: Returning an entity sends every field, including password hashes and internal flags, Response DTOs as the only output, and mass assignment through request bodies (a customer setting role=ADMIN), Stack traces, SQL and class names in error responses: server.error settings and ProblemDetail, Different messages for 'no such user' and 'wrong password' reveal accounts, Reviewing a response body field by field
        • Missing ownership checks (IDOR): IDOR: changing an id in the URL or body to reach another user's data, Finding IDOR in a code review: every endpoint that takes an id, Updates and deletes as well as reads; nested resources such as order items, Guessable ids, and why random ids alone are not a fix, Writing a negative test for every owned resource
        • Brute-force login and account lockout: Brute force and credential stuffing against a login endpoint, Counting failed logins with AuthenticationFailureBadCredentialsEvent and resetting on success, Temporary lockout after repeated failures, and the risk of locking out real users, Rate limiting by IP and by account (in the app or at the gateway), 429 Too Many Requests with Retry-After as a ProblemDetail
        • Logging sensitive data: What must never be logged: passwords, tokens, full card numbers, personal data, Accidental leaks: whole request bodies, toString() of entities and DTOs, Authorization headers, Masking values and overriding toString on records that hold secrets, What should be logged: sign-ins, failures and access denials as security events, Log levels in production, and who can read the logs
        • Keeping dependencies up to date: Vulnerable components: how a library flaw becomes your flaw (Log4Shell as the example), Spring Boot's managed versions, and upgrading through the parent version, mvn versions:display-dependency-updates and mvn dependency:tree, Vulnerability scanning with OWASP Dependency-Check and Dependabot, A safe upgrade routine: read the release notes, upgrade, run the tests
        • Practice: security code review: Review short Spring code samples and list every security mistake, Fix leaks, missing checks and logged secrets, Rank findings by risk, Interview drill: common security mistakes and how you would fix them
        • Mini project: ShopLite security review: Run the threat-model checklist against the ShopLite code, Fix findings: secrets, DTO leaks, IDOR tests and sensitive logging, Add failed-login lockout and a dependency scan to the build, Update SECURITY.md with findings, fixes and remaining risks
      • Security Mini Project: Secure ShopLite

        • Documenting secured endpoints in Swagger UI: A bearer-JWT SecurityScheme with springdoc-openapi and @SecurityRequirement, The Authorize button: logging in and calling secured endpoints from Swagger UI, Documenting 401, 403 and 409 responses with ProblemDetail examples, Keeping Swagger UI public in dev, and disabling or protecting it in prod
        • Practice: Spring Security review: Mixed questions across the whole section, Trace a request from token to controller to owner check, Fix a broken security configuration end to end, Interview drill: design security for an e-commerce API
        • Project: Secure ShopLite: Customer sign-up and JWT login with refresh and logout, Admin-only product, category and stock management, Customers place and view only their own orders; admins see all, Consistent 401/403 ProblemDetail responses and CORS for a frontend per profile, Swagger UI with the Authorize button, a full security test suite, and an updated README and SECURITY.md
  5. Stage 5: Work Like a Developer

    Learn professional software engineering

    • Testing, Debugging & Code Quality
    • Design Patterns & SOLID in Practice
    • Docker, Deployment & CI/CD Basics
    • Backend Architecture & System Design Fundamentals
    • Real-World Java Projects
    See this stage
    See all topics in Work Like a Developer
    1. Testing, Debugging & Code Quality

      Unit tests with JUnit, mocks with Mockito, testing Spring applications, using the debugger and keeping code clean.

      • Why Testing Matters

        • Manual testing vs automated testing: Checking ShopLite by hand: clicking, curl and console menus every release, Regressions: a change that silently breaks something that used to work, A first automated check in a single-file program: a tiny hand-rolled check(expected, actual) printing PASS/FAIL, What a test framework adds: discovery, reports, failing the build, Cost over time: manual checks grow, automated tests run in seconds
        • Unit, integration and end-to-end tests: Unit test: one class, no database, no network, milliseconds, Integration test: real pieces together (service + database, controller + JSON), End-to-end test: the whole app through its real interface (HTTP API), Which ShopLite bug each kind catches: a wrong discount, a bad SQL query, a broken URL, Speed, cost and confidence trade-offs of each kind
        • The test pyramid: Many unit tests, fewer integration tests, very few end-to-end tests, Why: feedback speed, failure precision and maintenance cost, The ice-cream cone anti-pattern: mostly slow manual and UI tests, Sketching the pyramid for ShopLite's product, order and security code, Where contract and smoke tests fit
        • What makes a test good: fast, isolated, readable: FIRST: fast, isolated, repeatable, self-checking, timely, One behaviour per test and a name that says it, Flaky tests and their causes: clock, random values, shared state, test order, network, Making time and randomness controllable (passing a Clock or a seed), Tests as documentation: reading a test tells you what the code promises
        • Tests in the Maven build: src/test/java mirrors src/main/java; test classes are not packaged in the jar, The junit-jupiter dependency with test scope (version 5.14.4) and the Surefire plugin, mvn test, reading the Surefire summary (Tests run, Failures, Errors, Skipped) and target/surefire-reports, A failing test fails the build; running one class or method with -Dtest=, Failsafe and *IT classes for slower integration tests; why -DskipTests is a last resort
        • Practice: testing basics: Classify tests as unit, integration or end-to-end, Spot what makes given tests slow, flaky or unreadable, Fix a Maven project whose tests do not run, Interview drill: why test, the pyramid, unit vs integration
        • Mini project: a ShopLite test plan and first tests: A one-page test plan for ShopLite: what to test at each level of the pyramid, Confirm shoplite-api runs its tests with mvn test, First unit tests for price and line-total calculations, Make one test fail on purpose, read the report, then fix it
      • JUnit 5 in Depth

        • Test structure: Arrange, Act, Assert: A test class, @Test methods and package-private visibility, Arrange, Act, Assert as three visible blocks, One reason to fail per test, Reading a failure: expected vs actual and the stack line in the test
        • Core JUnit assertions: assertEquals, assertNotEquals, assertTrue, assertFalse, assertNull, assertSame vs assertEquals and why equals() matters, Comparing doubles with a delta; BigDecimal with compareTo, assertAll to report several failures at once, Failure messages and message suppliers
        • Lifecycle: @BeforeEach, @AfterEach, @BeforeAll: A new test-class instance per test method, @BeforeEach and @AfterEach for fresh fixtures, @BeforeAll and @AfterAll must be static (or @TestInstance(PER_CLASS)), Shared mutable state between tests and order-dependent failures, Printing the lifecycle order to see it happen
        • Testing exceptions and timeouts: assertThrows returns the exception: checking type and message, Why try/catch/fail tests are fragile, assertDoesNotThrow for the happy path, assertTimeout vs assertTimeoutPreemptively and the @Timeout annotation
        • Parameterised tests with @ValueSource and @CsvSource: @ParameterizedTest with @ValueSource for many inputs, @CsvSource for input-expected rows, and @CsvFileSource, @NullAndEmptySource and @EnumSource, @MethodSource for objects, and custom display names with {0} and {arguments}, The junit-jupiter-params artifact
        • Readable assertions with AssertJ: assertThat(actual).isEqualTo(...) and the assertj-core dependency, Collections: hasSize, contains, containsExactly, extracting fields, Strings, numbers, BigDecimal isEqualByComparingTo and Optionals, assertThatThrownBy and assertThatExceptionOfType, Clearer failure messages, as() descriptions and SoftAssertions
        • Naming and organising tests: Naming styles: method_condition_result and should... sentences, @DisplayName and the display name generator, @Nested classes to group tests by scenario, @Tag, @Disabled with a reason, and running tagged groups from Maven, Test data helpers and builders to keep tests short
        • Practice: JUnit 5: Write tests for given classes in AAA form, Convert repeated tests to parameterised tests, Fix wrong assertions and leaking fixtures, Interview drill: lifecycle, assertThrows, parameterised tests
        • Mini project: a test suite for the ShopLite cart: A Cart class: add, remove, change quantity, total with BigDecimal, Lifecycle-managed fixtures and @Nested scenarios, Parameterised tests for quantity and price rules, Exception tests for invalid quantities and unknown products
      • Test-Driven Development

        • Red, green, refactor: Write a failing test first and watch it fail (red), Write just enough code to pass (green), Clean up with the tests as a safety net (refactor), Tiny steps, a test list and triangulation, A single-file TDD demo with a hand-rolled check method
        • TDD kata: a discount calculator, part 1: The rules: percentage discount, minimum order value, member bonus, Start with the simplest test: no discount, Add one rule per cycle and keep every test green, Refactor duplicated conditions into small methods
        • TDD kata: a discount calculator, part 2: New rules: a cap on the total discount and coupon codes, Changing rules: let a failing test show what broke, Parameterised tests for the rule table, Reviewing the final design that the tests shaped
        • Testing edge cases and boundaries: Equivalence partitions: one test per class of input, Boundary values: just below, at and just above a threshold, Empty, null, zero, negative and very large inputs, Money rounding with BigDecimal and RoundingMode.HALF_UP, Off-by-one bugs caught by boundary tests
        • When TDD helps and when it does not: Where TDD shines: business rules, bug fixes, pure logic, Where it struggles: UI layout, exploratory spikes, unknown APIs, Test-first for bug fixes: reproduce with a failing test, Common myths: TDD means no design, 100% coverage, slower delivery
        • Practice: TDD: Small katas: password strength, shipping cost, leap years, List boundary tests for given rules, Fix a test list that misses edge cases, Interview drill: TDD cycle and benefits
        • Mini project: ShopLite coupon rules with TDD: Coupon rules: expiry date, minimum basket, one use per customer, percentage or fixed, A test list first, then red-green-refactor for each rule, A controllable Clock for expiry tests, Boundary tests and a final refactor of the CouponService
      • Mocking with Mockito

        • Why mock: slow, external or unfinished dependencies: An OrderService that needs a repository, a payment gateway and an email sender, Slow, external or unfinished dependencies make unit tests impossible, Test doubles: replacing a dependency through constructor injection, A hand-written fake in a single-file program before any library
        • @Mock, @InjectMocks and when/thenReturn: The mockito-junit-jupiter dependency and @ExtendWith(MockitoExtension.class), @Mock and @InjectMocks (constructor injection) vs Mockito.mock(), when(...).thenReturn(...) and default answers (null, 0, empty), Argument matchers any(), eq() and the all-or-nothing matcher rule, Strict stubs and UnnecessaryStubbingException
        • verify and argument captors: verify that a call happened: times(1), never(), atLeastOnce(), verifyNoMoreInteractions and when not to use it, ArgumentCaptor to inspect what was passed, InOrder for sequence-sensitive calls
        • Stubbing exceptions: thenThrow for methods that return values, doThrow().when() for void methods, Testing error paths: payment declined, product not found, Consecutive stubbing and thenAnswer for computed results
        • Mocks vs stubs vs fakes: Dummy, stub, spy, mock and fake: what each one does, An in-memory fake repository vs a mocked repository, @Spy and partial mocks, and why they are rarely needed, State verification vs behaviour verification, Choosing the simplest double that works
        • Over-mocking and brittle tests: Signs: tests break on every refactor, mocks returning mocks, Do not mock value objects, records or types you do not own, Verifying implementation details instead of outcomes, Rewriting a brittle test to check results
        • Practice: Mockito: Write service tests with mocks and captors, Predict what a stubbed mock returns, Fix matcher, strict-stub and over-mocking mistakes, Interview drill: mock vs stub vs spy, @InjectMocks
        • Mini project: unit-test the ShopLite order service: OrderService.placeOrder with mocked product and order repositories, Stock checks, totals and the saved order captured with ArgumentCaptor, Error paths: unknown product, out of stock, invalid state, Verifying nothing is saved when a rule fails
      • Testing Spring Applications

        • Unit testing services without Spring: Constructor injection makes services plain objects to test, ProductService tested with Mockito and no application context, Speed comparison: milliseconds vs seconds for a context, What still needs Spring: wiring, JSON, SQL, security
        • @WebMvcTest and MockMvc for controllers: spring-boot-starter-test and the Boot 4 web MVC test starter, @WebMvcTest(ProductController.class) loads only the web layer, @MockitoBean replaces the service (@MockBean is gone in Boot 4), mockMvc.perform(get(...)) with status() and jsonPath() checks, Why a test fails with 'No qualifying bean' and how to fix it
        • Validation and error responses in controller tests: POST with a JSON body and content type, 400 ProblemDetail for invalid fields and unknown properties, 404 from ResourceNotFoundException through the global handler, Checking Location headers and 201 Created
        • @DataJpaTest for repositories: @DataJpaTest loads JPA, Flyway and repositories only, Embedded database vs a real MySQL with Testcontainers (and @AutoConfigureTestDatabase), TestEntityManager to arrange rows; rollback after each test, Testing derived queries, @Query methods and pagination
        • @SpringBootTest for full flows: @SpringBootTest with webEnvironment RANDOM_PORT, Calling the API with RestTestClient or MockMvc via @AutoConfigureMockMvc, A full flow: create a product, place an order, read it back, Context caching and keeping the full-test count small
        • Testing secured endpoints with mock users: spring-security-test and @WithMockUser with roles, 401 for anonymous, 403 for the wrong role, jwt() request post-processor for JWT resource servers, Ownership: a customer cannot read another customer's order
        • Test data and test profiles: @ActiveProfiles("test") and application-test.properties, @Sql scripts and test-data builders, Keeping tests independent: rollback, cleanup and unique values, Never pointing tests at a real database by accident
        • Practice: testing Spring applications: Pick the right slice for given tests, Write MockMvc and @DataJpaTest tests, Fix failing slice tests: missing beans, wrong profile, 403 instead of 200, Interview drill: @WebMvcTest vs @SpringBootTest, @MockitoBean
        • Mini project: test the ShopLite category API: Service unit tests for category rules (duplicate name, category in use), MockMvc tests for every category endpoint and its errors, Repository tests for name lookups, One full @SpringBootTest flow
      • Debugging

        • Breakpoints, step over, step into: Starting a single-file program in debug mode in IntelliJ and VS Code, Line breakpoints and the paused frame, Step over, step into, step out, resume and run to cursor, The call stack (frames) panel, Println debugging vs the debugger
        • Watching variables and evaluating expressions: The variables view: locals, fields, collections and toString(), Watches for values you check repeatedly, Evaluate expression while paused, Changing a value to test a theory, Dropping a frame to rerun a method
        • Conditional breakpoints: Breaking only when a condition is true (the 500th loop pass), Hit counts and logging breakpoints that do not suspend, Exception breakpoints: stop where an exception is thrown, Method and field-watch breakpoints and their cost
        • Reading stack traces from top to bottom: Exception type, message and the top frame, Finding the first frame in your own code among library frames, Caused by chains and '... n more', Helpful NullPointerException messages, Long Spring stack traces: where to look first
        • Debugging a running Spring Boot app: Running the app in debug mode and hitting a breakpoint with curl, Debugging a failing test, Remote debugging with -agentlib:jdwp on port 5005, Hot swap: what can change without a restart, Timeouts and threads while paused
        • A step-by-step bug hunting routine: Reproduce the bug reliably, Narrow it down: inputs, layers, divide and conquer, git bisect, Form a hypothesis and test it with the debugger or a log, Fix with a failing test first and check for the same bug elsewhere
        • Practice: debugging: Read stack traces and name the failing line, Choose the right breakpoint for a scenario, Find bugs in small programs, Interview drill: how do you debug a production issue
        • Mini project: hunt three bugs in ShopLite: Bug 1: an order total rounds wrongly, Bug 2: the last page of products is missing an item, Bug 3: a NullPointerException for a product without a category, Each fix arrives with a regression test
      • Logging for Troubleshooting

        • What to log at each level: Why System.out is not logging, System.Logger and java.util.logging in a single-file program, SLF4J in Spring Boot: TRACE, DEBUG, INFO, WARN, ERROR, What belongs at each level, with ShopLite examples, Changing levels per package
        • Parameterised log messages: {} placeholders instead of string concatenation, Logging exceptions as the last argument to keep the stack trace, Why log.error(e.getMessage()) loses information, Expensive messages: level checks and suppliers, Log and rethrow: logging the same error twice
        • Request ids to trace one request: Many requests interleaved in one log, MDC: putting a request id in every line, A servlet filter that sets and clears the id, and the X-Request-Id header, %X{requestId} in the log pattern, MDC and new threads
        • Logback configuration and log files: logging.level and logging.file.name in application properties, logback-spring.xml: appenders, encoders and patterns, Rolling files by size and date, and keeping history, Profile-specific logging and structured JSON logs
        • What never to log: Passwords, tokens, card numbers and personal data, Masking values and logging ids instead of objects, Log injection through newlines in user input, Too much logging: noise, cost and disk space
        • Practice: logging: Pick levels for given events, Rewrite concatenated and leaky log lines, Find a request in an interleaved log, Interview drill: logging levels, MDC, what not to log
        • Mini project: request logging for ShopLite: A filter logging method, path, status and time for every request, Request ids in MDC, the log pattern and the response header, Rolling log file for prod, readable console for dev, Review all ShopLite log lines for levels and secrets
      • Code Quality & Clean Code

        • Naming, small methods and clear intent: Names that reveal intent; avoiding abbreviations and noise words, Small methods that do one thing at one level of detail, Guard clauses instead of deep nesting, Comments that explain why, not what, Magic numbers to named constants
        • Code smells: duplication, long methods, god classes: Duplicated code and copy-paste bugs, Long methods and long parameter lists, God classes that know everything, Primitive obsession and feature envy, Spotting smells in a ShopLite class
        • Safe refactoring with tests and IDE tools: Tests first: characterisation tests for untested code, IDE refactorings: rename, extract method, extract variable, inline, move, Small steps with tests green and a commit after each, Refactoring vs changing behaviour
        • Code coverage with JaCoCo and what it does not tell you: Adding the jacoco-maven-plugin and reading the HTML report, Line vs branch coverage, A minimum coverage rule that fails the build, High coverage with no assertions: why 100% is not the goal
        • Static analysis with SonarLint: What static analysis finds: bugs, smells, security hotspots, SonarLint (now SonarQube for IDE) in IntelliJ and VS Code, Compiler warnings with -Xlint, Fixing vs suppressing a finding, and SonarQube in CI
        • Code review checklist: What reviewers check: correctness, tests, names, errors, security, Small pull requests and clear descriptions, Writing kind, specific review comments, Receiving feedback and a checklist for your own code
        • Practice: clean code: Name smells in given code, Refactor small methods step by step, Judge whether given tests justify their coverage, Interview drill: code smells, refactoring, coverage
        • Mini project: refactor the ShopLite order service: Characterisation tests around a long placeOrder method, Extract pricing, stock and validation into small classes, Coverage before and after with JaCoCo, Fix SonarLint findings and review the result with the checklist
      • Testing Mini Project: Test ShopLite

        • Test ShopLite: pricing and order rules: Test plan and test structure for shoplite-api, Unit tests for prices, totals, discounts and stock rules, Mockito tests for order placement and cancellation, Fix the bugs the tests reveal
        • Test ShopLite: controllers, validation and errors: MockMvc tests for products, categories and orders, 400, 404 and 409 ProblemDetail responses, Pagination parameters and response shape, Test helpers for JSON bodies
        • Test ShopLite: repository queries: @DataJpaTest for custom queries and pagination, Test data with @Sql and builders, Checking the N+1 fix stays fixed, A real MySQL run with Testcontainers
        • Test ShopLite: roles and ownership: 401 and 403 for anonymous users and wrong roles, Admin-only product management, Customers see only their own orders, One full @SpringBootTest login-to-order flow
        • Test ShopLite: coverage report and refactoring pass: JaCoCo report and a minimum coverage rule in the build, Finding untested branches that matter, A refactoring pass with the suite as a safety net, README: how to run the tests and what they cover
    2. Design Patterns & SOLID in Practice

      The design patterns used in real Java code and in interviews, applied together with SOLID principles.

      • SOLID Recap & Design Thinking

        • SOLID as design decisions, not definitions: One-line recap of each principle with a link back to the OOP section (no re-teaching), SRP decision: splitting a 'god' OrderService into pricing, payment and notification classes, OCP and LSP decision: adding a new payment type without editing checkout, and a subclass that breaks a contract, ISP and DIP decision: a fat Notifier interface split up, checkout depending on an abstraction, Five before/after mini-examples from the ShopLite order/payment/notification flow, each with the question that drove the change
        • Program to interfaces: designing the seams: Declared type vs runtime type in fields, parameters and return values, Finding the seams: what is likely to change (payment provider, notification channel), Constructor injection by hand: passing a PaymentGateway into Checkout, Swapping a fake implementation in a main-method test, Over-abstraction: an interface with one implementation that never changes
        • Favouring composition when designing classes: The subclass explosion: EmailSmsNotifier, EmailPushNotifier and friends, Rebuilding the same behaviour by holding a list of channels, Changing behaviour at runtime, which inheritance cannot do, When inheritance is still right: a true is-a with a stable base class, How composition prepares the ground for Strategy, Decorator and Composite
        • What a design pattern is and is not: A pattern as a named, reusable solution to a recurring design problem, The parts of a pattern: intent, problem, structure, consequences, Creational, structural and behavioural families and the Gang of Four catalogue, What patterns are not: libraries, copy-paste templates or goals in themselves, Map of the section: which pattern solves which ShopLite problem
        • Reading UML class diagrams: Class boxes: name, fields, methods and visibility symbols (+ - # ~), Interfaces and abstract classes in diagrams, Arrows: inheritance, implementation, association, dependency, Aggregation vs composition diamonds and multiplicity (1, 0..*, 1..*), Turning a ShopLite order diagram into Java classes and back
        • Design thinking practice: Name the violated principle in five short snippets, Fix a checkout class that creates its own dependencies, Replace an inheritance tree with composition, Translate a UML diagram to code and code to a diagram, Interview drill: 'How do SOLID principles relate to design patterns?'
        • Project: ShopLite order flow baseline design: Single-file Java program: Product, Cart, Order, PaymentGateway, Notifier and a public Demo class, Requirements: place an order, take payment, send a confirmation, Design applying SRP, DIP and composition, with a UML sketch, This baseline is the running example the rest of the section refactors with patterns, Self-check list: what will change, and where is the seam for it?
      • Creational Patterns

        • Singleton: one instance on purpose: Intent: exactly one shared instance (an AppConfig for ShopLite), Private constructor, static field and getInstance(), Eager vs lazy initialisation, Problems: global state, hidden dependencies, hard-to-test code, Breaking a naive singleton with reflection and serialization
        • Thread-safe singletons and why Spring beans replace them: Race condition in lazy getInstance() shown with two threads, synchronized method vs double-checked locking with volatile, Initialization-on-demand holder idiom, Enum singleton: safe against reflection and serialization, Spring singleton-scoped beans: one instance per container without static state
        • Simple factories and Factory Method: Problem: new CardPayment() scattered through checkout, Simple factory: PaymentFactory.create(type) with a switch, Static factory methods like List.of and Optional.of, Factory Method: subclasses decide which product to create, Adding a new payment type and counting the files touched
        • Abstract Factory: families of related objects: Problem: objects that must match (region-specific tax calculator, currency formatter, shipping), AbstractFactory interface with one create method per product, IndiaStoreFactory and UsStoreFactory implementations, Client code that never names a concrete class, Cost: adding a new product type changes every factory
        • Builder for objects with many fields: Telescoping constructors and why they hurt, Static nested Builder with fluent setters and build(), Validating required fields inside build(), Building immutable objects with final fields, Builder vs records and constructor parameters: when each fits
        • Prototype and copying objects (brief): Intent: create new objects by copying a configured template, Copy constructors as the preferred way (recap link to the OOP copying lessons), A registry of prototype products or cart templates, Shallow-copy bug: shared mutable lists between copies
        • Creational patterns practice: Pick the right creational pattern for five scenarios, Fix a lazy singleton that is not thread-safe, Convert a telescoping constructor to a builder, Replace scattered new calls with a factory, Interview drill: 'Which singleton implementation is best and why?'
        • Project: ShopLite payments and order creation: Extend the baseline single-file program from module 1, PaymentFactory creating Card, UPI and Wallet payments, Region StoreFactory supplying tax and shipping calculators, Immutable Receipt built with a Builder, Demo main showing output for two regions and three payment types
      • Structural Patterns

        • Adapter: wrapping an incompatible API: Problem: a third-party payment SDK with different method names and units (paise vs rupees), Object adapter implementing PaymentGateway and holding the SDK, Class adapter via inheritance and why object adapters are preferred, Translating exceptions and error codes at the boundary, JDK examples: Arrays.asList and InputStreamReader
        • Decorator: adding behaviour without subclassing: Problem: logging, retry and timing on a PaymentGateway without editing it, Decorator implements the interface and wraps another instance, Stacking decorators and why order matters, Decorator vs subclassing: avoiding the class explosion, Price decorators: gift wrap and express delivery add-ons
        • Decorators in Java I/O streams: Reading new BufferedReader(new InputStreamReader(...)) as a decorator chain, FilterInputStream and FilterReader as decorator base classes, Writing a custom UpperCaseReader decorator over StringReader, Closing the outer stream closes the whole chain
        • Proxy: lazy loading and access control: Proxy implements the same interface and controls access to the real object, Virtual proxy: loading a heavy ProductImage only when shown, Protection proxy: only admins can change prices, Caching proxy for repeated product lookups, Proxy vs decorator: same shape, different intent
        • Dynamic proxies and how Spring AOP uses them: java.lang.reflect.Proxy and InvocationHandler in a single-file example, A timing proxy generated for any interface, Spring AOP idea: advice wrapped around bean methods (short snippet, not run), JDK proxies vs CGLIB subclass proxies, Self-invocation: why calling this.method() skips the proxy
        • Facade: one simple entry point: Problem: checkout needs inventory, pricing, payment, shipping and notification calls, CheckoutFacade.placeOrder() hiding the subsystem steps, Facade does not block direct access to subsystems, Avoiding a facade that becomes a god class, Facade vs service layer in Spring applications
        • Composite: trees of objects: Problem: categories containing products and subcategories, Component interface with leaf and composite classes, Recursive operations: total price of a product bundle, Printing a category tree with indentation, Where composite appears: UI trees, file systems, menus
        • Structural patterns practice: Identify adapter, decorator, proxy, facade or composite in five snippets, Fix a decorator that forgets to delegate, Write an adapter for a legacy SMS API, Trace the output of a stacked decorator chain, Interview drill: 'Explain how java.io uses Decorator'
        • Project: ShopLite checkout facade: Single-file program grown from the module 2 project, Adapter for a fake third-party payment SDK, Logging and retry decorators around the gateway, Caching proxy for product lookups and a bundle composite, CheckoutFacade as the one entry point used by the Demo main
      • Behavioural Patterns

        • Strategy: swapping algorithms: Problem: one method with a branch per discount rule, Strategy interface and concrete strategies, Context class holding and switching a strategy at runtime, Choosing a strategy from configuration or user input, Strategy and the open/closed principle
        • Strategy with lambdas and functional interfaces: A strategy interface with one method is a functional interface, Passing lambdas and method references as strategies, Using built-ins: Function, BiFunction, Comparator, A Map<String, Strategy> registry instead of a switch, When a named class is clearer than a lambda
        • Observer: events and listeners: Problem: order placement must notify email, inventory and analytics, Subject with subscribe, unsubscribe and notify, Event objects carrying data vs pushing raw values, Pitfalls: listener exceptions, ordering and memory leaks, Listeners in the JDK (PropertyChangeListener) and Spring application events (snippet)
        • Template Method: fixed steps, custom details: Abstract class with a final template method, Abstract steps and optional hook methods, Example: report export as CSV and as plain text, Hollywood principle: the base class calls you, Template Method vs Strategy: inheritance vs composition
        • Command: actions as objects, with undo: Command interface with execute() and undo(), Cart commands: AddItem, RemoveItem, ApplyCoupon, Invoker keeping a history stack for undo and redo, Queuing and logging commands for later execution, Runnable as the simplest command in the JDK
        • Chain of Responsibility: request filters: Problem: order validation with stock, limit, fraud and address checks, Handler interface with a next handler, Stop-on-failure vs pass-through chains, Building the chain from a list in order, Where chains appear: servlet filters and logging handlers
        • State: objects that change behaviour with status: Problem: order status switch statements in every method, State interface with one class per status: Placed, Paid, Shipped, Delivered, Cancelled, Transitions owned by the states, invalid actions rejected, Enum-based state machine as a lighter alternative, Drawing the state diagram before coding
        • Behavioural patterns practice: Match six scenarios to Strategy, Observer, Template Method, Command, Chain or State, Replace a discount switch with lambdas, Add undo to a command that forgot to store old state, Fix a chain that never reaches the last handler, Interview drill: 'Explain Observer with a real example'
        • Project: ShopLite order lifecycle: Single-file program grown from the module 3 project, Validation chain before an order is accepted, Order status as a State machine with illegal-transition errors, Cart commands with undo, Template Method for printing invoices; Demo main walking one order end to end
      • Patterns in the JDK & Spring

        • Iterator and Comparator as patterns: Iterator pattern: Iterable, Iterator and the for-each loop, Writing a custom Iterable over a product catalogue page, Fail-fast iterators and ConcurrentModificationException, Comparator as Strategy: comparing, thenComparing, reversed, Collections.sort taking a strategy
        • Builders in HttpClient, Stream.Builder and more: StringBuilder: a mutable builder for strings, HttpClient.newBuilder() and HttpRequest.newBuilder() fluent chains, Stream.builder() for building a stream step by step, Factory methods in the JDK: List.of, Path.of, Executors, Spotting builder vs factory from an API's shape
        • Spring beans, factories and dependency injection as patterns: The container as a big factory: BeanFactory and ApplicationContext, Singleton scope vs the Singleton pattern, @Bean methods as factory methods (snippet), Constructor injection as DIP applied by a framework, Hand-written wiring in main vs container wiring compared
        • Template classes: JdbcTemplate and RestClient: Boilerplate JDBC steps vs JdbcTemplate doing the fixed steps, Callbacks (RowMapper) as the custom details, Template Method by callback instead of inheritance, RestClient's fluent API: builder plus template ideas (snippet), Writing a tiny RetryTemplate in plain Java
        • Proxies behind @Transactional: What Spring wraps around a @Transactional bean (diagram and snippet), Begin, commit and rollback inside the proxy, Self-invocation and private methods: why the annotation is ignored, Simulating a transactional proxy with java.lang.reflect.Proxy, Same mechanism behind @Cacheable and @Async
        • Filter chains in Spring Security: Servlet filters as Chain of Responsibility, SecurityFilterChain and the order of its filters (reading), How a request is stopped or passed on, Simulating a filter chain with auth and logging filters in plain Java, Where a custom filter fits in the chain
        • Patterns in the JDK and Spring practice: Name the pattern behind ten JDK and Spring APIs, Write a custom Iterable and a Comparator chain, Find the bug: @Transactional on a self-called method, Read a filter chain configuration and predict the request path, Interview drill: 'Which design patterns does Spring use?'
        • Project: a mini dependency-injection container: Single-file Java program: a tiny container with register and get, Factories as Supplier lambdas and singleton caching, Wiring the ShopLite checkout through the container, A timing proxy added by the container around services, Comparing the result with what Spring does for you
      • Choosing & Refactoring to Patterns

        • Refactoring long if-else and switch to Strategy: Smell: the same switch on type repeated in several methods, Step-by-step refactor of shipping cost rules, output kept identical, Moving the choice to one place: a map or factory, Enum with behaviour as a lighter option, When a short switch should stay a switch
        • Removing duplication with Template Method: Smell: two classes with near-identical step sequences, Extracting the common skeleton into a base class, Pulling differing steps into abstract methods and hooks, Alternative: passing lambdas into one method, Checking the output is unchanged after refactoring
        • When a pattern makes code worse: Pattern fever: factories of factories for one class, YAGNI and KISS as checks before adding a pattern, Cost of indirection: more files and harder tracing, Simplifying an over-engineered design back to plain code, Questions to ask before introducing a pattern
        • Strategy vs State: Same class diagram, different intent, Who chooses: the client (Strategy) or the object itself (State), Do implementations know about each other?, Side-by-side: payment strategy vs order state
        • Adapter vs Decorator vs Proxy: All three wrap an object: what changes in each, Adapter changes the interface; Decorator adds behaviour; Proxy controls access, Facade vs Adapter: simplify vs translate, Comparison table with ShopLite examples, Identifying the pattern from a code snippet
        • Design patterns interview questions: How to answer: intent, structure, example, trade-off, Frequent questions: singleton thread safety, factory vs abstract factory, builder use, 'Which patterns have you used?' with ShopLite examples, Patterns in Java and Spring questions, Coding a pattern on a whiteboard in ten minutes
        • Refactoring to patterns practice: Refactor a notification switch into strategies, Remove duplication from two export classes, Undo an unnecessary pattern, Name the wrapper pattern in four snippets, Mock interview: five rapid-fire pattern questions
        • Project: refactoring a legacy ShopLite checkout: Start from one long single-file checkout class with switches and duplication, Refactor in small steps, checking output stays the same, Strategy for shipping, Template Method for invoices, State for status, Leave simple parts simple and record why, Before/after comparison of the class diagram
      • Low-Level Design Interview Problems

        • A method for LLD rounds: Clarifying requirements and scope with the interviewer, Finding entities, their fields and responsibilities, Relationships and a quick class diagram, Picking patterns where they solve a stated need, Coding the core flow first, then extensions; managing the time
        • LLD: parking lot system: Requirements: levels, spot sizes, vehicle types, tickets and fees, Entities: ParkingLot, Level, Spot, Vehicle, Ticket, Spot assignment strategy and fee strategy, Thread safety when two cars take the same spot, Single-file Java design with a demo run
        • LLD: movie ticket booking: Requirements: cities, theatres, shows, seats and bookings, Seat locking to stop double booking, Pricing strategy by seat type and show time, Booking states: held, confirmed, cancelled, Single-file Java design with a demo run
        • LLD: elevator system: Requirements: multiple cars, floor and cabin requests, Elevator states: idle, moving up, moving down, maintenance, Dispatcher strategy: nearest car vs least busy, Simulating steps in a loop with printed output, Single-file Java design with a demo run
        • LLD: splitting expenses between friends: Requirements: users, groups, expenses and balances, Split types: equal, exact and percentage as strategies, Validating splits that do not add up, Simplifying debts into the fewest payments, Single-file Java design with BigDecimal amounts and a demo run
        • LLD: vending machine with the State pattern: Requirements: select item, insert coins, dispense, return change, States: Idle, HasMoney, Dispensing, OutOfStock, Inventory and change calculation, Rejecting invalid actions per state, Single-file Java design with a demo run
        • LLD practice: mock rounds: Timed mock: library management system, Find design flaws in a given parking lot solution, Extend the booking design with coupons, Short drills: entities and relationships for five systems, Interview drill: handling follow-up 'what if' questions
        • Project: food delivery LLD for ShopLite-style ordering: Requirements: restaurants, menus, cart, orders and delivery agents, Agent assignment strategy and order State machine, Observer notifications to customer and restaurant, Single-file Java design with a demo of one full order, Write-up: requirements, class diagram and trade-offs
      • Design Patterns Practice & Review

        • Practice: Strategy for discounts and shipping costs: Percentage, flat and buy-one-get-one discounts as strategies, Weight and distance shipping strategies with free-shipping threshold, Combining strategies for a final total with BigDecimal, Adding a festival discount without editing existing classes
        • Practice: order notification events: OrderPlaced, OrderShipped and OrderCancelled event classes, Event publisher with email, SMS and inventory listeners, Isolating a failing listener so others still run, Unsubscribing and testing listener order
        • Practice: Builder for complex order objects: Order with items, address, coupon, gift note and delivery slot, Required vs optional fields and validation in build(), Immutable Order with defensive copies of item lists, Nested builders for address and line items
        • Review and improve an existing design: Code-review checklist: SOLID, coupling, naming, pattern fit, Reviewing a supplied ShopLite module with real flaws, Writing review comments that explain why, Applying the improvements and comparing before/after
        • Design patterns section review: One-page summary of every pattern: intent, structure, ShopLite use, Pattern selection quiz with scenarios, Code reading: name the patterns in a mixed program, Final interview drill covering SOLID, patterns and LLD
        • Milestone project: ShopLite order engine with patterns: Single-file Java order engine: catalogue, cart, checkout and order lifecycle, Builder for orders, Strategy for discounts and shipping, Observer events for notifications, State for order status, Facade for checkout, Adapter for a payment SDK, Demo main running three scenarios with exact expected output, Design write-up: class diagram, pattern choices and what was left simple
    3. Docker, Deployment & CI/CD Basics

      Package your application with Docker, run it with a database, automate builds and tests, and deploy it online.

      • Why Containers?

        • Development, test and production environments: The "works on my machine" story: different JDK, MySQL version, OS paths and missing env vars between laptops and servers, What dev, test (CI) and production each are for, who uses them and what may differ (data, URLs, secrets, log level), Twelve-factor idea in one rule: same build artifact everywhere, only configuration changes, Runnable single-file Java program: AppConfig reads APP_ENV, DB_URL and PORT from System.getenv with defaults and prints the effective config, Failing fast: the same program throws a clear error when a required variable is missing in prod (shown output for both runs)
        • Virtual machines vs containers: Diagram: hardware, hypervisor, guest OS per VM vs one host kernel shared by containers, What a container really is: an isolated process (namespaces) with limited resources (cgroups) and its own filesystem, Start-up time, size and density compared with a small table (seconds vs minutes, MB vs GB), Why Docker on Windows and macOS runs a small Linux VM underneath (WSL 2 / Docker Desktop VM), When a VM is still the right choice: different kernel, strong isolation, legacy apps
        • Images, containers and registries: Image = read-only template made of layers; container = a running (or stopped) instance with a thin writable layer, Class vs object analogy for Java developers: one image, many containers, Image names decoded: registry/namespace/repository:tag (docker.io/library/eclipse-temurin:25-jre), Registries: Docker Hub, GitHub Container Registry, cloud registries; official images and why to pin tags, docker pull, docker images and image digests (reading code with Sample output)
        • Installing Docker Desktop: Installing Docker Desktop on Windows (WSL 2 backend), macOS (Apple silicon vs Intel) and Docker Engine on Linux, Checking the install: docker version and docker info (Sample output), client vs server, Docker Desktop dashboard tour: containers, images, volumes, resource limits, Common install problems: virtualization disabled in BIOS, WSL not updated, "Cannot connect to the Docker daemon", permission denied on Linux (docker group), Alternatives in one line each: Podman, Rancher Desktop, colima
        • Running your first container: docker run hello-world and what each line of its output means (pull, create, start, print, exit), docker run -it --rm eclipse-temurin:25-jdk jshell: a JDK without installing one, Running a single-file Java program inside a container with a bind mount: java Hello.java (reading code + Sample output), Container lifecycle: created, running, exited; why the container stops when its main process ends, Unable to find image locally and manifest unknown (wrong tag) errors explained
        • Practice: containers basics: Match terms to definitions: image, container, layer, registry, tag, daemon, VM or container? Five scenarios to decide, Decode five image names and spot the unpinned one, Fix the env-var config program that crashes with a NullPointerException instead of a clear message, Interview drill: "What problem does Docker solve?" and "Container vs VM?" in 60 seconds
        • Project: make ShopLite environment-ready: Problem statement: list every value in shoplite-api that differs between dev, test and prod (DB URL, user, password, JWT secret, port, log level), Reference application.yml mapping each to an environment variable with dev defaults (${DB_URL:jdbc:mysql://localhost:3306/shoplite}), Reference .env.example committed, real .env in .gitignore, README section: "Environments" table and how to run with docker run eclipse-temurin to prove the JDK is not needed locally, Labelled reference files (not run in the lesson)
      • Docker Essentials

        • docker run, ps, stop, rm and logs: docker run flags that matter: -d, --name, --rm, -it, docker ps and ps -a: reading the STATUS and PORTS columns, docker stop vs kill: SIGTERM, 10-second grace, SIGKILL; docker start and restart, docker logs -f --tail 50 and why apps must log to stdout, Cleaning up: docker rm, docker image rm, docker system prune (and what it deletes); "name already in use" conflict
        • Port mapping: Runnable single-file Java server with com.sun.net.httpserver on port 8080 returning {"status":"UP"}, Why localhost:8080 fails until -p 8080:8080 is added: container network is isolated, -p host:container explained with two examples (-p 9090:8080), EXPOSE is documentation only, Binding inside the container: 0.0.0.0 vs 127.0.0.1 and why the latter is unreachable, "port is already allocated" error and how to find the process using the port
        • Environment variables in containers: -e KEY=value and --env-file app.env with the same Java config program from module 1, Image defaults with ENV vs runtime overrides, precedence order, docker inspect and docker exec env to see what a container actually received, Spring Boot relaxed binding: SPRING_DATASOURCE_URL maps to spring.datasource.url, Why secrets in -e show up in docker inspect and shell history, and what to do instead (env files outside Git, secret stores later)
        • Volumes for data that must survive: Demo: write a file in a container, remove the container, data is gone, Named volumes (-v shoplite-data:/var/lib/mysql) vs bind mounts (-v ./src:/app) vs tmpfs, docker volume ls, inspect, rm and where Docker stores volume data, When to use each: database data = named volume, source code in dev = bind mount, Bind mount gotchas on Windows paths and file permissions
        • Running MySQL in a container: docker run mysql:8.4 with MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD, a named volume and -p 3307:3306, Init scripts in /docker-entrypoint-initdb.d and why they only run on an empty volume, Connecting from the host: mysql client, Workbench and a JDBC URL on port 3307, Waiting for "ready for connections" in docker logs before connecting, Errors: Access denied (changed password but old volume), Communications link failure (wrong port), port 3306 already used by local MySQL
        • Shell into a container to debug: docker exec -it <name> sh/bash and when neither exists (distroless, minimal images), Running mysql inside the MySQL container to check tables, docker inspect for IP, mounts, env and exit code; docker stats for CPU and memory, Reading exit codes: 0, 1, 137 (OOM or kill), 143 (SIGTERM), docker cp to copy a log or heap dump out, and why changes made by exec are lost on recreate
        • Practice: Docker essentials: Write the command for each task: detached named container, follow logs, map port, pass env file, mount volume, Fix five broken docker run commands (wrong -p order, missing volume, unquoted env, conflicting name, wrong tag), Read docker ps -a output and explain why each container exited, Predict: is the MySQL data still there after rm / rm -v / volume rm?, Interview drill: volumes vs bind mounts; what happens on docker stop
        • Project: ShopLite on a MySQL container: Problem statement: replace the locally installed MySQL with a mysql:8.4 container for shoplite-api, Reference shell script scripts/db-up.sh (docker run with env file, volume, port, healthy wait loop), Reference .env.example and application.yml values pointing at port 3307, Flyway applies migrations on app start against the container (Sample output of startup log), README: start, stop, reset database commands; labelled as not run
      • Dockerising a Spring Boot App

        • Writing a Dockerfile line by line: Smallest Dockerfile for a single-file Java health server: FROM, WORKDIR, COPY, EXPOSE, CMD, Each instruction explained: what it creates (a layer or metadata) and when it runs (build vs run), CMD vs ENTRYPOINT, exec form vs shell form and why exec form gets signals, docker build -t shoplite-hello:0.1 . and reading the build output (Sample output), Packaging the Spring Boot fat jar: COPY target/*.jar app.jar and ENTRYPOINT ["java","-jar","/app/app.jar"]
        • Choosing a base image: JDK vs JRE images: build with a JDK, run with a JRE, eclipse-temurin variants: full (Ubuntu), -alpine, and distroless/chiselled options; size comparison table, Pinning: 25-jre vs latest vs digest, and why latest breaks builds, Trust and updates: official images, CVE scanning with docker scout in one example, JVM in a container: container-aware memory, -XX:MaxRAMPercentage=75 via JAVA_TOOL_OPTIONS
        • Multi-stage builds with Maven: Problem: building the jar on the host means "works on my machine" again, Stage 1 FROM maven/eclipse-temurin JDK AS build: COPY pom, src, ./mvnw package -DskipTests, Stage 2 FROM JRE: COPY --from=build only the jar, Why the final image has no Maven, no source and no JDK (size before/after), Where tests run: in CI, not in the image build (cross-reference to the CI module)
        • Layer caching for faster builds: How the build cache works: an instruction is reused until it or its inputs change, then everything below rebuilds, Order matters: COPY pom.xml and ./mvnw dependency:go-offline before COPY src, BuildKit cache mount: RUN --mount=type=cache,target=/root/.m2, Spring Boot layered jars: java -Djarmode=tools extract --layers and copying dependencies, spring-boot-loader, snapshot-dependencies, application separately, Reading build output: CACHED vs re-run steps (Sample output of two builds)
        • .dockerignore and image size: Build context: everything sent to the builder, and the slow "transferring context" problem, .dockerignore for a Maven project: target/, .git, .idea, *.iml, .env, logs, Secrets leaking into images through COPY . . and why layers keep deleted files, Measuring: docker images, docker history and comparing three Dockerfile versions, Size tips that matter vs ones that do not (jlink custom runtime mentioned as advanced)
        • Running as a non-root user: Why root in a container is risky: escape bugs, writable files, mounted volumes, Creating a user: RUN groupadd/useradd (or addgroup -S on Alpine) and USER spring:spring, File ownership: COPY --chown and writable directories for logs or temp files, Checking: docker exec whoami and docker inspect Config.User, Graceful shutdown in containers: exec-form ENTRYPOINT receives SIGTERM, server.shutdown=graceful (runnable single-file Java shutdown hook demo with shown output)
        • Practice: Dockerfiles: Review a bad Dockerfile and list every problem (latest tag, JDK runtime, root user, COPY . . before pom, shell-form CMD), Reorder instructions to maximise cache hits, Write a .dockerignore from a project tree, Predict which steps rebuild after changing a controller vs pom.xml, Interview drill: multi-stage builds, layers, and why non-root
        • Project: a production Dockerfile for shoplite-api: Problem statement: an image under ~250 MB, rebuilt in seconds after a code change, running as non-root, Reference Dockerfile: multi-stage, Maven cache mount, layered jar extraction, temurin 25 JRE, USER, exec ENTRYPOINT, JAVA_TOOL_OPTIONS, Reference .dockerignore, docker build and docker run against the MySQL container from module 2 (Sample output: startup log, curl /actuator/health), README: build and run commands; files labelled as reference, not run
      • Docker Compose

        • compose.yaml: services, ports and volumes: From long docker run commands to one compose.yaml (file name compose.yaml vs docker-compose.yml, no version key), services: image vs build, ports, environment, volumes, restart, Top-level volumes for named volumes, docker compose up -d, ps, logs -f api, down vs down -v, YAML pitfalls: indentation, quoting "8080:8080" and yes/no booleans
        • Networking between containers: The default project network and DNS by service name, Why the app uses jdbc:mysql://db:3306 inside Compose but localhost:3307 from the host, ports vs expose: published to the host vs reachable only on the network, Keeping the database unpublished in production-like setups, Debugging: docker compose exec api sh, then ping/nc db 3306; "UnknownHostException: db" and "Connection refused" explained
        • Health checks and start-up order: Problem: depends_on starts MySQL first but the app connects before MySQL is ready, healthcheck for MySQL (mysqladmin ping) with interval, timeout, retries, start_period, depends_on: condition: service_healthy, App health check: runnable single-file Java server exposing /health that turns UP after a simulated warm-up, then curl/wget in healthcheck, Why the app should still retry connections (Hikari initialization-fail-timeout) and restart: on-failure
        • Environment files and secrets: .env next to compose.yaml for variable substitution (${MYSQL_PASSWORD}) vs env_file: for container env, Required variables: ${JWT_SECRET:?JWT_SECRET is required}, docker compose config to see the resolved file, Compose secrets mounted at /run/secrets and Spring Boot configtree: import, Committing .env.example only; never .env (link to the Git section)
        • A local development setup with Compose: Two ways to work: everything in Compose vs only the database in Compose and the app in the IDE, spring-boot-docker-compose dependency: Boot starts compose.yaml and wires the DataSource automatically, Adding tools: Adminer or phpMyAdmin service under a dev profile (profiles: [tools]), compose.override.yaml for dev-only settings (debug port 5005, bind mounts), docker compose up --build and watch; rebuilding after code changes
        • Practice: Docker Compose: Fix a compose.yaml with five bugs (localhost DB URL, wrong indentation, missing volume declaration, no healthcheck, password in file), Convert three docker run commands into one compose.yaml, Read docker compose ps/logs output and explain why the api keeps restarting, Decide ports vs expose for each service, Interview drill: how containers find each other; start-up order
        • Project: ShopLite stack with one command: Problem statement: docker compose up gives a working shoplite-api + MySQL with seed data and Swagger UI, Reference compose.yaml: db with healthcheck and volume, api built from the module 3 Dockerfile, depends_on healthy, env from .env, Reference .env.example and compose.override.yaml with Adminer, Smoke test: curl /actuator/health and GET /api/products (Sample output), README: up, logs, reset data; labelled as reference files, not run
      • Integration Tests with Testcontainers

        • Why in-memory databases can hide bugs: Quick recap with a link to Section 18 (spring-datajpatest-repositories, spring-boot-integration-tests) instead of re-teaching slice tests, Four real H2 vs MySQL differences: SQL dialect functions, case sensitivity/collation, JSON and ENUM columns, DECIMAL rounding and LIMIT/locking behaviour, Flyway scripts written for MySQL failing on H2 (or H2 MODE=MySQL passing when MySQL fails), The rule: test against the same database engine and version as production, Cost: Docker required on dev machines and CI, slower start-up, and how it pays off
        • Adding Testcontainers to a Spring Boot project: Dependencies: spring-boot-testcontainers, testcontainers junit-jupiter and mysql modules (versions from the Boot BOM), First test: @Testcontainers, @Container static MySQLContainer<>("mysql:8.4") and @DynamicPropertySource, What happens on run: image pull, Ryuk cleanup container, random host port (Sample output log), @DataJpaTest with @AutoConfigureTestDatabase(replace = NONE), Errors: "Could not find a valid Docker environment", slow first pull, port conflicts that cannot happen with random ports
        • @ServiceConnection and a shared container: @ServiceConnection replaces @DynamicPropertySource for the DataSource, @TestConfiguration with a @Bean @ServiceConnection MySQLContainer, imported with @Import, Sharing one container across test classes: singleton/static container pattern and Spring context caching, Running the app locally against a Testcontainer: TestShopliteApplication with SpringApplication.from(...).with(...), Keeping tests independent on a shared database: @Transactional rollback vs cleaning tables, unique test data
        • Running Flyway migrations in tests: Flyway runs automatically on the test context: the same V1..Vn scripts as production (link to Section 16 Flyway lessons), ddl-auto=validate in tests catches entity/schema mismatches, Test data: test-only migrations in src/test/resources/db/testdata via spring.flyway.locations vs @Sql per test, A test that proves migrations apply cleanly from empty (Sample output of Flyway log), Failing migration in a test: reading the Flyway error and fixing the script
        • Practice: Testcontainers: Spot the H2-only bug in a repository query and write the test that exposes it, Convert a @DynamicPropertySource test to @ServiceConnection, Fix a test suite that starts a new container per class and takes minutes, Fix tests that pass alone but fail together on a shared database, Interview drill: why Testcontainers over H2; how containers are cleaned up
        • Project: ShopLite repository tests on real MySQL: Problem statement: move the Section 18 ShopLite repository and integration tests from H2 to MySQL Testcontainers, Reference MySqlTestcontainersConfig with @ServiceConnection and container reuse, Reference tests: product search with collation, order totals with DECIMAL, Flyway validate test, Reference TestShopliteApplication for local runs without installed MySQL, Sample output: mvn verify log with container start and test summary; labelled as not run
      • CI/CD with GitHub Actions

        • What CI and CD mean: Continuous integration: every push is built and tested, small merges, fast feedback, Continuous delivery vs continuous deployment: a release is always ready vs every green main goes live, A pipeline diagram: push → build → test → package image → deploy, and where each check stops a bad change, Pipeline principles: fast, reproducible, same commands as local (./mvnw verify), fail loudly, GitHub Actions, GitLab CI and Jenkins compared in one table
        • Workflow files: triggers, jobs and steps: .github/workflows/ci.yml: name, on (push, pull_request, workflow_dispatch, branches filter), jobs, runs-on: ubuntu-latest, steps with uses (actions) vs run (shell), Jobs run in parallel unless needs: is set; matrix in one example (Java 21 and 25), Contexts and expressions: ${{ github.sha }}, ${{ secrets.X }}, if: conditions, Reading the Actions tab: logs per step, re-run, common YAML and "action not found" errors
        • Building and testing a Maven project: actions/checkout and actions/setup-java (temurin, java-version 25), run: ./mvnw -B verify and why -B (batch mode); chmod +x mvnw on Linux runners, Testcontainers in CI: Docker is available on ubuntu-latest runners, Uploading test reports and the jar with actions/upload-artifact; failing the build on test failures, Reading a failed run: finding the failing test in the log (Sample output)
        • Caching dependencies: Why the first run downloads half of Maven Central, setup-java cache: maven and what it keys on (pom.xml hash), actions/cache explained: key, restore-keys, cache hit vs miss in the log, Docker layer cache in CI: cache-from/cache-to type=gha with docker/build-push-action, Measuring the gain: run time before and after (Sample output)
        • Building and pushing a Docker image: docker/setup-buildx-action, docker/login-action to ghcr.io with GITHUB_TOKEN and permissions: packages: write, docker/metadata-action for tags: sha, branch, semver from git tags, docker/build-push-action with push only on main (if: github.ref == 'refs/heads/main'), Repository secrets vs variables vs environments; never echo secrets, Pulling the pushed image locally to prove it works (Sample output)
        • Branch protection with required checks: Rulesets / branch protection on main: require a pull request, require status checks to pass, Choosing which job names are required and why renaming a job breaks the rule, Require branches to be up to date, block force pushes, require review, The flow: feature branch → PR → CI green → review → merge (link to the Git section), Status badge in the README
        • Practice: GitHub Actions: Fix a workflow with five bugs (bad indentation, wrong trigger branch, missing checkout, no permissions for packages, secret printed), Add caching to a slow workflow and predict cache hits, Split one job into build-test and image jobs with needs:, Read a failed run log and name the cause, Interview drill: CI vs CD; what your pipeline does on a pull request
        • Project: ShopLite CI pipeline: Problem statement: every PR runs tests with Testcontainers; every push to main publishes ghcr.io/<user>/shoplite-api:<sha>, Reference .github/workflows/ci.yml with build-test job (setup-java cache, ./mvnw -B verify, upload reports), Reference image job (needs: build-test, buildx, login, metadata, build-push with gha cache), Branch protection checklist and README badge, Sample output of a green run; files labelled as reference, not run
      • Deploying to the Cloud

        • Hosting options for a student project: IaaS (a VM), PaaS / container platforms and serverless explained with what you manage in each, Options for a container + MySQL: a PaaS such as Render, Railway or Fly.io; a small VM with Docker Compose; AWS/Azure/GCP container services, Comparison table: free tier limits, sleeping apps, cold starts, regions, ease of setup (note: check current pricing, it changes), Choosing for a portfolio project: simple, cheap, always-on enough for a demo, Cost safety: budgets, alerts and shutting things down
        • Managed MySQL databases: What "managed" gives you: backups, patches, monitoring, failover, Creating a database and an app user with least privilege (not root), Connection strings with SSL (sslMode=REQUIRED), allowed IPs / private networking, Running Flyway against the managed database on first app start, Errors: connection timeouts from firewall rules, too many connections and Hikari pool size on small plans
        • Configuration and secrets in production: Where config lives: platform environment variables and secret stores, never the image or Git, The prod profile: SPRING_PROFILES_ACTIVE=prod, ddl-auto=validate, no stack traces in responses, INFO logging, Runnable single-file Java ConfigCheck: validates required variables, masks secrets when printing (JWT_SECRET=****), Generating a strong JWT secret and rotating it, What to do when a secret leaks: rotate, revoke, rewrite history is not enough
        • Deploying a container image: Deploying the GHCR image to a container platform: image URL, port (PORT env and server.port=${PORT:8080}), env vars, health check path, Deploying to a VM: docker compose pull && docker compose up -d, Reading the first deploy logs and fixing "app failed to bind to port" and out-of-memory restarts, Sizing memory: JVM in 512 MB with MaxRAMPercentage, Verifying: curl https://<app>/actuator/health and an API call (Sample output)
        • Custom domains and HTTPS: DNS basics: A and CNAME records, TTL, propagation, Platform-managed TLS certificates (Let's Encrypt) and why the app itself stays on HTTP behind the proxy, server.forward-headers-strategy=framework so redirects and Swagger URLs use https, Updating CORS allowed origins for the real frontend domain (link to Section 17), Checking with curl -I and the browser padlock; mixed-content errors
        • Automatic deploys from the main branch: Platform auto-deploy on push vs a deploy job in GitHub Actions (deploy hook or CLI), deploy job with needs: [build-test, image], environment: production and its secrets, Deploying the exact SHA-tagged image that passed tests, not latest, Post-deploy smoke test step: curl --fail with retries on /actuator/health, Manual approval for production with environment protection rules
        • Practice: deploying to the cloud: Pick a hosting option for three scenarios and justify, Find the problems in a production config (root DB user, ddl-auto=update, secret in YAML, DEBUG logging), Diagnose four deploy failures from log excerpts (port, memory, DB SSL, missing env var), Order the steps of a safe automatic deploy, Interview drill: how you deployed your project and kept secrets safe
        • Project: ShopLite goes online: Problem statement: deploy the shoplite-api image with a managed MySQL and reach it over HTTPS, Reference application-prod.yml and the list of platform environment variables (values not shown), Reference deploy job added to ci.yml with environment: production and a smoke test, Deployment checklist: DB user, SSL, Flyway, CORS, forward headers, memory, Sample output: deploy log and curl of /actuator/health; labelled as not run
      • Running in Production

        • Health and readiness endpoints with Actuator: Quick recap of /actuator/health from Section 15 (spring-boot-actuator-health), then liveness vs readiness: restart me vs do not send me traffic, management.endpoint.health.probes.enabled, /actuator/health/liveness and /readiness, the db indicator in readiness, Exposure and security: expose only health and info publicly, show-details when-authorized, separate management port, Runnable single-file Java server with /live and /ready using com.sun.net.httpserver: ready only after startup, not ready during shutdown (shutdown hook, shown output), Wiring probes into the platform health check and Compose healthcheck
        • Reading production logs: Logs go to stdout; the platform collects them (link to Section 18 logging lessons, no re-teaching of levels), Structured JSON logs with Spring Boot logging.structured.format.console=ecs/logstash, Runnable single-file Java program that prints JSON log lines with timestamp, level, requestId and message, then filters them by requestId, Searching logs: time window, level, request id from an error response; following one failed request, Reading a production stack trace and correlating with the deploy time
        • Basic metrics: response time and error rate: The few numbers that matter: request rate, error rate, latency (p50/p95/p99), plus JVM memory and DB pool usage, Why averages lie: runnable single-file Java program computing average vs p95 and error rate from a list of request timings and status codes, Micrometer and /actuator/metrics/http.server.requests; tags for uri, status, outcome, Prometheus endpoint and a dashboard in one picture (Grafana or the platform's built-in metrics), Simple alerts: error rate above 5% for 5 minutes, health check failing, uptime monitor
        • Rolling back a bad release: Spotting a bad release: errors spike right after a deploy, Rollback options: redeploy the previous SHA image, platform rollback button, git revert and let CI redeploy, Database changes and rollback: Flyway is forward-only; expand-and-contract migrations so old code still works, Graceful shutdown and rolling deploys: server.shutdown=graceful and readiness to avoid dropped requests, A short incident write-up: what happened, impact, fix, prevention
        • Database backups: Managed automated backups and point-in-time recovery: retention and what they do not cover, mysqldump --single-transaction from a container or host and restoring into a fresh container (reading code with Sample output), A backup you have not restored is not a backup: monthly restore test, Scheduling a dump with a GitHub Actions schedule or cron, and storing it off the server encrypted, Backups before risky migrations and the 3-2-1 rule
        • Practice: running in production: Liveness or readiness? Classify six checks, From a metrics summary and log excerpt, decide: roll back, fix forward or ignore, Fix an Actuator config that exposes env and heapdump publicly, Write the rollback steps for a release that added a NOT NULL column, Interview drill: "Your API is slow in production. What do you do?"
        • Project: ShopLite production runbook: Problem statement: make the deployed ShopLite observable and recoverable, Reference application-prod.yml: probes, exposure, structured logs, graceful shutdown, Prometheus metrics, Reference scripts/backup.sh and restore.sh and a scheduled backup workflow, Reference RUNBOOK.md outline: health URLs, where logs are, how to roll back, how to restore, Sample output of probe and metrics endpoints; labelled as not run
      • Deployment Mini Project: Ship ShopLite

        • Ship ShopLite 1: Dockerfile and Compose: Milestone brief: from a repo clone to a running ShopLite (API, MySQL, Swagger UI) with one command, Requirements: multi-stage non-root Dockerfile, .dockerignore, compose.yaml with health checks, .env.example, Full reference files: Dockerfile, .dockerignore, compose.yaml, compose.override.yaml, Acceptance checks: docker compose up, health UP, seeded products listed, data survives restart (Sample output), Labelled reference files, not run in the lesson
        • Ship ShopLite 2: Testcontainers integration tests in CI: Brief: all integration tests run against MySQL 8.4 Testcontainers locally and in GitHub Actions, Requirements: shared @ServiceConnection container, Flyway-built schema, tests for products, orders and auth, Full reference test configuration and two representative integration tests, CI job running ./mvnw -B verify with Maven cache and test report upload, Sample output of a green test run; labelled as not run
        • Ship ShopLite 3: pipeline from push to deploy: Brief: PR = build and test; main = test, push SHA image, deploy, smoke test, Full reference .github/workflows/ci.yml with build-test, image and deploy jobs, Branch protection with the required check and production environment approval, Rollback procedure: redeploy previous SHA, Sample output of a full pipeline run; labelled as not run
        • Ship ShopLite 4: production configuration and secrets: Brief: production-safe settings with no secret in Git, image or logs, Full reference application-prod.yml (validate, probes, structured logs, forward headers, CORS, graceful shutdown), Secrets list and where each lives (platform env, GitHub environment secrets); least-privilege DB user, Backup schedule and restore check, Security review checklist before going live
        • Ship ShopLite 5: live URL with Swagger UI in your README: Brief: a portfolio-ready repo a recruiter can try in two minutes, Exposing Swagger UI in production safely (read-only demo user, rate limiting note) and the OpenAPI link, Reference README: live URL, Swagger link, CI badge, architecture diagram, run locally with Compose, tech stack, Final verification checklist: HTTPS, health, a full order flow with curl against the live URL (Sample output), How to talk about the project in an interview: decisions, trade-offs and what you would do next
    4. Backend Architecture & System Design Fundamentals

      Layered architecture, caching, scaling and the system design basics asked in entry-level interviews.

      • Thinking About Systems

        • What system design is (and is not): High-level design (boxes, data flow, scale) vs low-level design (classes, patterns) and where Section 19 fits, Functional requirements for ShopLite: browse products, place order, track order, Non-functional requirements: latency, availability, consistency, scalability, durability, cost, Turning a vague prompt ('design a shop') into a written requirements list with numbers, How interviewers judge freshers: clarity, reasoning and trade-offs over buzzwords
        • Latency, throughput and availability: Latency vs throughput with a checkout-queue analogy; p50, p95 and p99 percentiles, Single-file Java simulation: timing 1,000 fake requests and printing average vs p99 latency, Availability as nines: 99.9% vs 99.99% converted into minutes of downtime per month, Availability of components in series vs in parallel (redundancy) with worked numbers, Why the average hides slow users: tail latency in plain words
        • Single server to many servers: how systems grow: Stage 1 diagram-in-words: one box running app plus database, Stage 2: separate database server; stage 3: several app servers behind a load balancer, Stage 4: cache, read replicas and a CDN; stage 5: queues and background workers, Which bottleneck triggers each step (CPU, DB connections, disk, network), Single points of failure at every stage and how each step removes one
        • Trade-offs and a step-by-step approach for design rounds: Classic trade-offs: consistency vs availability, latency vs cost, simplicity vs flexibility, Writing a trade-off as 'we chose X, we gave up Y, because Z', The 6-step design-round framework: clarify, estimate, API, data model, high-level design, deep dive and bottlenecks, Time budget for a 45-minute round and what to say aloud at each step, Worked walkthrough: the framework applied to a 'design a library catalogue' prompt
        • System design thinking practice: Classify 10 requirements as functional or non-functional, Convert availability percentages to downtime and pick the right target for three apps, Spot the single point of failure in three described architectures, Rewrite a weak fresher answer using the 6-step framework, Interview drill: 'What is the difference between latency and throughput?' and four more short questions
        • Project: ShopLite requirements and baseline architecture: Problem statement: ShopLite expects to grow from 1,000 to 1 million users, Write functional and non-functional requirements with target numbers, Baseline single-server design as a diagram-in-words with the request flow for checkout, List bottlenecks and single points of failure and the growth stages that fix them, Worked design write-up and a review checklist to compare against
      • Backend Architecture

        • Layered architecture at system level: Recap of controller, service, repository layers (no re-teaching of Spring), The same layers seen as tiers: client, web/app tier, data tier, Where cross-cutting concerns live: auth, logging, validation, caching, Single-file Java simulation: a request passing through three layer classes with a printed trace, Smells: controllers talking to the database, services returning HTTP objects
        • Monolith and modular monolith: What a monolith is: one deployable, one database, and why it is a good default, Pain points as teams grow: tangled packages, slow builds, risky deploys, Modular monolith: module boundaries by business area (catalogue, orders, payments) with public interfaces, Package layout for ShopLite as a modular monolith and the rule 'modules talk through interfaces only', Single-file Java demo: an OrderModule calling a CatalogueApi interface instead of its internals
        • Microservices: what they are and why not to start with them: Microservice definition: independently deployable service owning its own data, What you gain: independent scaling and deploys, team autonomy, What you pay: network calls, partial failure, distributed data, observability, ops cost, Why fresher projects and startups start with a monolith; signals that justify splitting, Diagram-in-words: ShopLite split into catalogue, order and payment services and the new failure points
        • Stateless application servers: Stateful vs stateless server: where the session and cart live, Single-file Java simulation: two 'servers' with in-memory carts losing data when the balancer switches, Fix: moving state to a shared store (a Map standing in for Redis/DB) and to JWT tokens, Why stateless servers can be added, removed and restarted freely, What still has state: uploads, local caches, scheduled jobs, and how to handle each
        • Synchronous calls vs background jobs and queues: Synchronous request: user waits for email, invoice PDF and stock update, The queue idea: producer, queue, consumer; at-least-once delivery in plain words, Single-file Java simulation with BlockingQueue: checkout returns fast, a worker thread sends 'emails', Failure handling: retries, dead-letter queue, duplicate messages and idempotent consumers, Where real queues fit (RabbitMQ, Kafka, SQS) shown as names and roles only
        • Backend architecture practice: Pick monolith, modular monolith or microservices for four described companies and justify, Find and fix the stateful bug in a two-server simulation, Decide sync vs queue for eight ShopLite actions, Fix a layering violation in a short code sample, Interview drill: 'Monolith vs microservices?', 'What does stateless mean?' and more
        • Project: ShopLite modular monolith with an order queue: Problem statement: checkout is slow because it sends email and updates stock inline, Single-file Java simulation: catalogue, orders and notifications modules behind interfaces, OrderPlaced event pushed to a BlockingQueue and handled by a worker thread, Stateless checkout: cart kept in a shared store Map, not in the server object, Design write-up: module diagram-in-words, sample output and what would change with a real broker
      • API Design at Scale

        • Idempotency keys for safe retries: The double-charge problem: client retries after a timeout and the order is created twice, Which HTTP methods are idempotent by definition and why POST is not, Idempotency-Key header: store the key with the first response and replay it, Single-file Java simulation: OrderApi with a ConcurrentHashMap of keys, retried request returns the same order id, Edge cases: key expiry, same key with a different body (reject), concurrent duplicates with putIfAbsent
        • Pagination for very large lists: Why returning all rows fails: memory, latency, timeouts, Offset/limit pagination and why deep pages get slow (OFFSET 1000000), Cursor (keyset) pagination: WHERE id > lastId ORDER BY id LIMIT n, Single-file Java simulation over a sorted list: offset vs cursor and the 'item shifted between pages' bug, Response shape: items, nextCursor, hasMore; capping page size on the server
        • Timeouts and retries with backoff: Why every remote call needs a timeout; connect vs read timeout, Which errors to retry (timeouts, 503) and which not (400, 404), Exponential backoff with jitter and a maximum attempt count, Single-file Java simulation: a flaky service failing 60% of the time (seeded Random) and a retry helper printing delays, Retry storms and the circuit breaker idea in plain words (closed, open, half-open)
        • Backward-compatible API changes: Safe changes: adding optional fields, new endpoints; breaking changes: renaming, removing, changing types, Tolerant readers: clients ignore unknown fields, Versioning options: /v1 in the path, header versioning, and when to bump, Deprecation process: announce, run both, measure usage, remove, Worked example: changing ShopLite 'price' from a number to {amount, currency} without breaking old apps
        • Handling slow work asynchronously: Slow work examples: report export, bulk import, image processing, 202 Accepted plus a job id and a status endpoint (polling) pattern, Webhooks/callbacks as an alternative to polling, Single-file Java simulation: ExecutorService runs a 'report' job while the client polls status, Job states (PENDING, RUNNING, DONE, FAILED) and storing results for download
        • API design at scale practice: Mark ten API changes as breaking or safe, Fix a retry loop that retries 400 errors forever with no delay, Convert offset pagination to cursor pagination, Find the duplicate-order bug in a create endpoint without idempotency, Interview drill: 'What is idempotency?', 'How do you paginate a billion rows?' and more
        • Project: ShopLite reliable order API simulation: Problem statement: mobile clients on bad networks retry orders and list huge order histories, Single-file Java simulation: idempotent POST /orders with an Idempotency-Key map, Cursor-paginated order history over in-memory data, Client-side retry helper with backoff calling a flaky simulated server, Design write-up: API contract, versioning note and sample output
      • Caching

        • Where caches live: browser, CDN, application, database: Why caching works: reads outnumber writes, memory is faster than disk and network, Cache layers on a ShopLite product page: browser, CDN, app memory, shared cache, database buffer pool, HTTP caching headers: Cache-Control max-age, ETag and 304 Not Modified, Hit ratio and how it changes average latency (worked numbers), What not to cache: per-user secrets, rapidly changing stock counts
        • Cache-aside, write-through and expiry: Cache-aside read path: check cache, miss, load from DB, put in cache, Single-file Java simulation: a Map as the 'DB' with an artificial delay and a second Map as the cache, printing hits and misses, Write-through and write-behind compared with cache-aside, Adding TTL expiry: storing value plus expiresAt and checking it on read, Choosing a pattern for the product catalogue vs order status
        • Cache invalidation and stale data: Why invalidation is hard: the cache and DB can disagree, Update DB then delete cache vs update cache; the race that leaves stale data, Simulation: a price update leaving a stale cached price, and the fix, Cache stampede (thundering herd) on a popular key and fixes: locking, early refresh, Deciding how stale is acceptable per data type
        • Eviction policies: LRU and TTL: Why caches need eviction: limited memory, LRU, LFU and FIFO compared on one access sequence, Building an LRU cache with LinkedHashMap(accessOrder=true) and removeEldestEntry, Building LRU from scratch with HashMap plus a doubly linked list for O(1) get/put, Combining an LRU size limit with TTL expiry and printing evictions
        • Spring @Cacheable and Redis as a shared cache: Reading code: @EnableCaching, @Cacheable, @CacheEvict, @CachePut on a ProductService (runsIn + sample output), Cache keys and conditions; the self-invocation proxy pitfall, In-memory cache per server vs a shared cache when there are many servers, Redis as the usual shared cache: key-value, TTL, common commands (GET, SET EX, DEL) as reading only, Reading config: spring.cache.type=redis and serialization notes
        • Caching practice: Trace an access sequence through an LRU cache of size 3, Fix a cache-aside method that never invalidates on update, Choose cache layer and TTL for six kinds of ShopLite data, Calculate average latency from a hit ratio, Interview drill: 'How does LRU work?', 'What is a cache stampede?' and more
        • Project: ShopLite product cache simulation: Problem statement: the product page is slow and the database is overloaded, Single-file Java simulation: ProductRepository Map with a delay, LRU cache with TTL in front of it, Invalidation on price update and hit/miss statistics printed after a run, Comparing simulated total time with and without the cache, Design write-up: where Spring @Cacheable and Redis would replace the simulation
      • Databases at Scale

        • Indexes and query tuning as the first step: Recap: full scan vs index lookup (link back to the SQL section, no re-teaching), Finding slow queries: slow query log and EXPLAIN as reading only, N+1 queries and fetching only needed columns, Single-file Java simulation: linear search vs a HashMap/TreeMap 'index' over 1 million rows with operation counts, Cost of indexes: slower writes, more storage; why tune before adding servers
        • Connection pools and their limits: Why opening a DB connection per request is slow, Pool basics: max size, idle, wait timeout; HikariCP settings as reading only, Single-file Java simulation: a Semaphore-based pool with 5 connections and 20 threads, showing waits and timeouts, Total connections = servers x pool size vs the database max_connections limit, Symptoms of an exhausted pool and fixes: shorter transactions, the right pool size
        • Replication and read replicas: Primary handles writes, replicas copy and serve reads, Synchronous vs asynchronous replication and replication lag, Read-your-own-writes problem after placing an order, and fixes, Single-file Java simulation: a router sending writes to the primary and reads round-robin to lagging replicas, Failover: promoting a replica when the primary dies
        • Sharding and partitioning (concept): Partitioning within one database (by date) vs sharding across servers, Shard keys: user id, hash vs range, and hot-shard problems, Single-file Java simulation: hash(userId) % N and the mass re-mapping when N changes, Consistent hashing ring with virtual nodes using TreeMap, showing fewer keys move, Costs: cross-shard queries, joins and transactions
        • SQL vs NoSQL and the CAP theorem: NoSQL families: key-value, document, wide-column, graph with one use case each, Choosing for the right reasons: data shape, query patterns, consistency needs, team skills, Why ShopLite orders stay in MySQL and where a document or key-value store could help, CAP in plain words: during a network partition choose consistency or availability, Eventual consistency, a PACELC note and common myths in interview answers
        • Databases at scale practice: Pick the first fix for four slow-database scenarios (index, pool, replica, shard), Calculate total connections for a fleet and compare with max_connections, Choose a shard key for orders and explain hot spots, Pick SQL or NoSQL for five data sets, Interview drill: 'Replication vs sharding?', 'Explain CAP' and more
        • Project: ShopLite database scaling plan: Problem statement: the orders table reaches 500 million rows and reads overload the primary, Single-file Java simulation: read/write router with replicas plus consistent-hash sharding of orders by userId, Printed distribution of keys per shard before and after adding a shard, Design write-up: indexes first, then replicas, then sharding, with trade-offs, Sample output and a checklist for reviewing the plan
      • Load Balancing & Scaling

        • Vertical vs horizontal scaling: Scale up (bigger machine) vs scale out (more machines) with cost and limit comparison, What must be true to scale out: stateless servers, shared data, Auto-scaling on CPU or request count in plain words, Worked numbers: one server handles 500 RPS, how many for 4,000 RPS with headroom and one spare, Which ShopLite parts scale out easily and which do not
        • Load balancer algorithms: round robin, least connections: What a load balancer does; L4 vs L7 in plain words, Round robin load balancer in Java with AtomicInteger, Weighted round robin for servers of different sizes, Least connections in Java and when it beats round robin (long requests), IP hash and random choice briefly; simulation printing request distribution
        • Health checks and failover: Liveness vs readiness health checks; Spring Actuator /actuator/health as reading only, Single-file Java simulation: balancer skipping a server marked unhealthy after failed checks, Thresholds: fail after N checks, recover after M, Failover for the load balancer itself and for databases (active-passive), Graceful shutdown: draining connections before removing a server
        • Sticky sessions and CDNs for static content: Sticky sessions: how they work (cookie or IP hash) and their problems (uneven load, lost sessions), Why stateless servers with a shared session store or JWT are easier, CDN basics: edge servers, origin, cache hit at the edge, What to put on a CDN: images, JS, CSS; cache headers and file versioning (app.3f2a.js), Diagram-in-words: ShopLite request path with CDN, load balancer and app servers
        • Load balancing and scaling practice: Trace 10 requests through round robin and least connections, Fix a round robin balancer that is not thread-safe, Compute servers needed for given traffic and failure tolerance, Choose CDN or app server for eight resources, Interview drill: 'How does a load balancer know a server is down?' and more
        • Project: ShopLite load balancer simulation: Problem statement: ShopLite sale-day traffic and one server crashing mid-sale, Single-file Java simulation: pluggable strategies (round robin, least connections) behind an interface, Health checks marking a server down and traffic failing over, Printed per-server request counts and failed request count, Design write-up: final architecture with CDN, balancer and stateless servers
      • Rate Limiting & Protection

        • Why rate limit: Threats: abusive clients, scrapers, brute-force logins, buggy retry loops, Protecting shared resources and keeping fairness between users, Rate limiting vs throttling vs load shedding in plain words, Where limits sit: API gateway, load balancer, application, Real examples: login attempts, OTP sends, public API tiers
        • Fixed window, sliding window and token bucket: Fixed window counter in Java and the boundary-burst problem, Sliding window log with a Deque of timestamps, Sliding window counter approximation, Token bucket and leaky bucket ideas: capacity, refill rate, bursts, Comparison table: memory, accuracy, burst behaviour
        • Implementing a token bucket in Java: TokenBucket class: capacity, tokens, refillPerSecond, lastRefill, Lazy refill on each tryAcquire using elapsed time from an injectable clock, Making it thread-safe with synchronized and testing with several threads, Simulation printing allowed/rejected per request with a fake clock for repeatable output, Per-key buckets in a ConcurrentHashMap and cleaning idle buckets
        • Where to apply limits and returning 429: Choosing the key: per user, per IP, per API key, per endpoint; NAT and shared IP pitfalls, Tiered limits (free vs paid) and stricter limits on login and OTP, HTTP 429 Too Many Requests, Retry-After and X-RateLimit-* headers, Reading code: a Spring HandlerInterceptor using the token bucket (runsIn + sample output), Distributed limits across servers: why a shared counter (Redis INCR with expiry) is needed
        • Rate limiting practice: Trace requests through fixed window vs token bucket and compare results, Fix a non-thread-safe limiter, Choose keys and limits for five ShopLite endpoints, Fix a client that ignores Retry-After, Interview drill: 'Token bucket vs leaky bucket?' and more
        • Project: ShopLite API rate limiter: Problem statement: a scraper and a login brute-force attack hit ShopLite, Single-file Java simulation: per-key token buckets with different limits for /login and /products, Simulated clients producing 200/429 responses with Retry-After values, Summary report of allowed and rejected requests per client, Design write-up: moving the limiter to a gateway with a shared Redis counter
      • Back-of-the-Envelope Estimation

        • Useful numbers for estimation: Powers of two and data sizes: KB, MB, GB, TB, PB, Latency numbers: memory, SSD, network within a datacenter, cross-continent, Bytes per record: ids, timestamps, short strings, a typical order row, Seconds per day (86,400, about 10^5) and rounding rules, Single-file Java helper that prints byte counts in human units
        • Estimating daily users to requests per second: DAU x actions per user / 86,400 = average RPS, Peak factor (2-10x) and read/write ratio, Worked example: ShopLite with 1 million DAU, Single-file Java estimator printing average and peak RPS, Sanity checks: comparing with what one server can handle
        • Estimating storage and bandwidth over years: Records per day x bytes per record x days x years, Adding replication factor, indexes and growth, Images and media dominate: separating object storage from DB storage, Bandwidth: requests x response size, Worksheet: 5-year storage for ShopLite orders and product images
        • Using estimates to pick a design: From numbers to decisions: one DB or replicas, cache or not, shard or not, Rules of thumb: comfortable range for a single MySQL server, cache memory for the hot set (80/20), Worked example: sizing a cache from a hot-set estimate, Presenting estimates aloud in an interview in under 3 minutes, Common estimation mistakes: false precision, ignoring peak, mixing units
        • Estimation practice: Five timed estimation drills (photo app, chat app, URL shortener, ShopLite, logs), Find the unit mistake in three worked estimates, Convert estimates into server, cache and storage counts, Estimate cache memory for a hot set, Interview drill: 'Estimate QPS for 10M DAU' and more
        • Project: ShopLite capacity estimation worksheet: Problem statement: plan ShopLite for 5 million users over 5 years, Single-file Java estimator taking inputs and printing RPS, storage, bandwidth and cache size, Filled worksheet with every assumption written down, Design decisions derived from each number, Sample output and a comparison with the baseline design from module 1
      • Classic Design Questions

        • Design a URL shortener: Requirements and estimates: writes vs reads, 7-character codes, storage over 5 years, API: POST /urls, GET /{code} with 301 vs 302 redirect, Code generation: base62 of a counter vs hash plus collision check, in a single-file Java simulation, Data model, cache for hot links, and scaling the read path, Extras: custom aliases, expiry, click analytics counted asynchronously
        • Design Pastebin: Requirements: create paste, read by link, expiry, size limit, Storing text: metadata in the DB, content in object storage, Key generation reused from the URL shortener and why ids must be unguessable, Expiry cleanup job and CDN caching for popular pastes, Single-file Java simulation: paste store with TTL and size limit
        • Design a rate limiter as a service: Requirements: many API servers sharing one limit, low added latency, Placement: gateway vs sidecar vs library, Shared counter store (Redis) and atomic increment with expiry, as reading only, Race conditions and fail-open vs fail-closed decisions, Rule configuration per client tier and monitoring rejected traffic
        • Design a notification system: Requirements: email, SMS, push; user preferences; retries, Architecture: API, a queue per channel, workers, third-party providers, Templates, deduplication and idempotent sends, Rate limits per user and quiet hours, Single-file Java simulation: queues, channel workers and retry with a dead-letter list
        • Design a news feed (basic version): Requirements: post, follow, read a feed sorted by time, Fan-out on write vs fan-out on read and the celebrity problem, Feed cache per user and pagination with cursors, Single-file Java simulation: follow graph and fan-out on write into per-user feed lists, Storage choices, and ranking as a later extension
        • Explaining the design of your own project: A 2-minute structure: problem, users, architecture, data, one hard problem, what you would change, Drawing your project's architecture in words and boxes, Answering 'how would it handle 10x users?' for your project, Worked example: explaining ShopLite end to end, Pitfalls: overclaiming scale, buzzwords without reasons
        • Classic design questions practice: Timed outline drills for URL shortener and Pastebin, Find the flaw in a weak notification design, Choose a fan-out strategy for three feed scenarios, Fix a base62 encoder bug, Interview drill: follow-up questions interviewers ask on each classic problem
        • Project: URL shortener design and simulation: Problem statement: a ShopLite share-link shortener for 100 million links, Estimation, API and data model write-up, Single-file Java simulation: base62 codes, cache-aside with LRU, redirect lookup and click counting via a queue, Sample output with hit ratio and click totals, Design write-up with a diagram-in-words and trade-offs
      • System Design Practice & Review

        • Mock design round with a checklist: The full checklist: requirements, estimates, API, data model, architecture, deep dive, bottlenecks, wrap-up, Full worked mock round: 'Design an online ticket waiting queue' with interviewer prompts, Handling hints and changing requirements mid-round, Self-scoring rubric for a design answer, Time checkpoints across a 45-minute round
        • Drawing clear architecture diagrams: Standard boxes: client, CDN, load balancer, service, cache, DB, queue, worker, Showing request flow with numbered arrows; read vs write paths, The diagram-in-words notation used in this course, Before/after: a cluttered vs a clear diagram, Labelling data stores and sync vs async arrows
        • Common mistakes in fresher answers: Jumping to microservices and Kafka without numbers, Skipping requirements and estimates, Ignoring failure: no single-point-of-failure analysis, Cache without invalidation, sharding without a shard key, Rewriting weak answers into strong ones
        • System design interview questions and short answers: 30 short questions with 2-3 line answers across all modules, Concept pairs: cache vs CDN, replication vs sharding, horizontal vs vertical, Tricky follow-ups and how to say 'it depends' correctly, Mixed exercises: estimate, pick a design, find a flaw, Rapid-fire round
        • Milestone project: ShopLite at scale: Problem statement: ShopLite for 5 million users with a sale-day peak, Design document: requirements, estimates, API, data model, architecture diagram-in-words, trade-offs, Single-file Java simulation tying together load balancer, stateless servers, LRU cache, token-bucket limiter and order queue, Failure drill: one server and the cache fail, and the output shows recovery, Self-review with the mock-round checklist and sample output
    5. Real-World Java Projects

      Build complete backend projects from requirements to deployment, ending with a capstone for your portfolio.

      • Real-World Java Projects

        • Project: build and ship the URL Shortener API: Short code generation and collisions, Redirects with 301 vs 302, Click counts and expiry dates, In-memory caching of popular links, Rate limiting link creation, Tests, Docker and deployment, Milestones: links CRUD, redirect, stats and expiry, cache, rate limit, ship, Submit the GitHub repository with README and live link, Extensions: QR codes, per-day click charts, Redis cache, Interview questions about your URL shortener
        • Project: build and ship the Personal Expense Tracker API: Users, categories and expenses, JWT sign-up and login, Monthly reports with aggregate queries, Budgets and alerts with a scheduled job, Filtering, sorting and pagination, CSV export of expenses, Milestones: auth, categories and expenses, filters and paging, reports, budgets and alerts, CSV and ship, Submit the GitHub repository with README and live link, Extensions: recurring expenses, shared group budgets, PDF statement, Interview questions about your expense tracker
        • Project: build and ship the Event Ticket Booking API: Events, venues, seats and bookings, Seat holds that expire, Preventing double booking with locks and constraints, Idempotent payment confirmation (simulated), Booking confirmation emails sent in the background, Concurrency tests, Milestones: events and seats, holds, double-booking protection, payments, emails, tests and ship, Submit the GitHub repository with README and live link, Extensions: waitlist, QR ticket check-in, seat categories with prices, Interview questions about your booking system
        • Project: build and ship the Online Exam & Quiz Platform API: Question banks, tests and sections, Roles: faculty, student and admin, Timed attempts with a server-side clock and auto-submit, Randomised questions and answer-hiding, Auto-grading, negative marking and results, Leaderboards and result reports with caching, Milestones: question bank, tests, attempts with timer, grading, results and leaderboard, ship, Submit the GitHub repository with README and live link, Extensions: CSV question import, section-wise cut-offs, analytics per question, Interview questions about your exam platform
        • Capstone project: build, ship and present the Campus Placement Portal: Roles: student, company recruiter and placement officer, Job postings, eligibility rules and applications, Resume upload and application status workflow, Search with filters, paging and caching, Security, validation, auditing and Flyway migrations, Full test suite, Docker Compose, CI/CD and live deployment, Code review checklist and final refactoring, Architecture diagram and API documentation, Explaining design choices and trade-offs, Project questions interviewers ask, Adding the project to your resume and GitHub profile, Milestones: auth and roles, profiles and jobs, eligibility and applications, workflow and uploads, search and caching, ship and present, Submit the GitHub repository with README, architecture diagram, API docs and live link, Extensions: interview scheduling, analytics dashboard API, email digests, Interview questions about your capstone
  6. Stage 6: Get Job Ready

    Prepare for your first software job

    • Java Technical Interview Preparation
    • Placement Assessments & Career Preparation
    See this stage
    See all topics in Get Job Ready
    1. Java Technical Interview Preparation

      The Java, OOP, collections, DSA and backend questions interviewers ask, with clear answers, follow-ups and debugging rounds.

      • How Technical Interviews Work

        • Interview Rounds: Online Test, Technical and Managerial: Campus placement flow in India: aptitude + online coding test, technical round(s), managerial/HR round, Online test format: Java MCQs, output prediction, 1-3 coding problems on platforms like HackerRank/AMCAT-style tests, Technical round: core Java, OOP, DSA, project questions; how service vs product companies differ, Managerial round: project ownership, teamwork, scenario questions, What each round eliminates candidates for, with a sample timeline
        • What Interviewers Look For Beyond the Right Answer: Signals scored: fundamentals, problem-solving process, communication, code quality, honesty, Answer structure: definition, small Java example, where it is used (worked for 'What is polymorphism?'), Weak vs strong answers to the same question, side by side, Thinking aloud: narrating assumptions while solving, Saying 'I don't know' well: what you do know, how you would find out; never bluffing
        • Choosing What to Revise for Your Target Role: Core modules for every fresher: Core Java, OOP, Collections, output prediction, DSA, projects, mock, Optional modules: Streams (Stage 3), Multithreading/JVM (Stage 3), Backend/Spring/DB (Stages 4-5), Mapping role types (service fresher, product SDE, Java backend) to modules, Using earlier sections (1-22) to re-learn a weak topic before drilling, Making a personal revision tracker with weak-topic notes
        • Practice: Framing Interview Answers: Rewrite five weak answers into definition-example-use form, Think-aloud transcript: spot what the candidate should have said, Handling a question you cannot answer: three rehearsed scripts, Round identification quiz: which round asks which question
      • Core Java Questions

        • JDK, JRE, JVM and Platform Independence Questions: Recap: JDK contains compiler and tools, JRE runs, JVM executes bytecode (revisit Section 1 Getting Started, Section 11), Model answer: 'Why is Java platform independent?' and why the JVM itself is not, Is Java fully object-oriented? Is it compiled or interpreted? (JIT in one line), javac/java flow on a one-file program; what a .class file holds, Traps: confusing JRE with JVM, saying 'Java is 100% OOP'
        • Primitives, Wrappers and Autoboxing Questions: Recap: 8 primitives, sizes and defaults; wrapper classes (revisit Section 1 Variables & Data Types), Autoboxing and unboxing: what the compiler inserts, Predict the output: Integer cache, 127 == 127 vs 128 == 128, NullPointerException from unboxing a null Integer, Questions: why wrappers exist, int vs Integer in collections, char arithmetic
        • String Immutability, the String Pool and == vs equals: Recap: String is immutable and final (revisit Section 1 Strings, Section 3 References, Casting & Immutability), Model answer: why String is immutable (pool, security, hashing, thread safety), Literal vs new String(): how many objects are created; intern(), Predict the output: == vs equals on literals, new, concatenation and compile-time constants, Traps: s.concat() without assignment, comparing with == in conditions
        • String vs StringBuilder vs StringBuffer: Comparison table: mutability, thread safety, speed, Why + in a loop is slow; StringBuilder rewrite, Common methods asked: append, insert, reverse, deleteCharAt, toString, Coding question: reverse a string and check palindrome with StringBuilder, Trap: StringBuilder does not override equals
        • static, final and the main Method Questions: Recap: static members belong to the class; static blocks run once (revisit Section 3 Static & Final), final variable, method and class; final vs finally vs finalize, Why main is public static void; can main be overloaded; String[] args, Predict the output: static block and constructor order, Traps: static method cannot use this; final reference with mutable object
        • Is Java Pass by Value or Pass by Reference?: Model answer: Java is always pass by value; object references are copied (revisit Section 1 Methods, Section 3 References), Predict the output: modifying a field vs reassigning the parameter, Swap two Integers in a method: why it fails, Arrays passed to methods: changes are visible, Diagram-style explanation to give on a whiteboard
        • Exceptions: Checked vs Unchecked, finally, throw vs throws: Recap: Throwable hierarchy, Error vs Exception (revisit Section 1 Exception Basics, Section 9 Exceptions in Depth), Checked vs unchecked with examples; throw vs throws, finally: when it runs, when it does not (System.exit), try-with-resources, Custom exceptions and multi-catch questions, Traps: catching Exception too broadly, swallowing exceptions, catch order compile error
        • Practice: Core Java Rapid-Fire Drill: 20 rapid-fire questions with 30-second model answers, Predict-the-output set across wrappers, strings, static and exceptions, Two short coding questions: count characters, reverse words, Spot-the-wrong-answer: candidate answers with hidden mistakes
      • OOP Questions

        • The Four Pillars of OOP with Your Own Examples: One-line definition plus a tiny Java example for each pillar (revisit Section 3 modules), Encapsulation vs abstraction: the classic confusion, Compile-time vs runtime polymorphism, Types of inheritance in Java; why no multiple class inheritance (diamond problem), Real-world analogies that interviewers accept and ones they reject
        • Overloading vs Overriding and Their Rules: Comparison table: signature, return type, access, exceptions, binding time, Can static, private or final methods be overridden?, Covariant return types and @Override, Predict the output: overload resolution with null, int vs long vs Integer, Traps: changing only the return type, reducing visibility
        • Abstract Class vs Interface: Comparison: state, constructors, multiple inheritance, access modifiers (revisit Section 3 Abstraction & Interfaces), default, static and private interface methods (Java 8/9), Diamond conflict with two default methods and how to resolve it, When to choose which: model answer with a payment example, Functional and marker interfaces in one line each
        • Composition vs Inheritance: IS-A vs HAS-A; association, aggregation, composition (revisit Section 3 Composition & Relationships), Why 'favour composition over inheritance': fragile base class example, Refactor an inheritance hierarchy to composition, Follow-up questions: when inheritance is right
        • The equals and hashCode Contract: Recap: the contract rules (revisit Section 3 Object Class & Equality), Predict the output: HashSet with equals overridden but not hashCode, Writing correct equals and hashCode with Objects.equals/Objects.hash, Mutable fields used in hashCode: the lost-key bug, Questions: can two unequal objects share a hash code? why override both?
        • Immutable Classes and Records: Steps to write an immutable class: final class, private final fields, no setters, defensive copies, Defensive copy trap with a List or Date field, Records as concise immutable data carriers; what records generate, Benefits asked: thread safety, safe map keys, caching, Trap: record with a mutable list component
        • SOLID in One Minute Each: One-minute answer per principle with a tiny before/after (full treatment in Section 19 SOLID Recap & Design Thinking), Single responsibility and open/closed with a discount example, Liskov: the square-rectangle question, Interface segregation and dependency inversion in Spring terms, Interview angle only: pointer to Section 19 Low-Level Design Interview Problems
        • Practice: OOP Interview Drill: Explain-with-example round for 10 OOP questions, Predict the output: overriding, overloading, polymorphic calls, Fix a broken equals/hashCode and a leaky 'immutable' class, Design mini-question: model shapes with interfaces and composition
      • Collections & Generics Questions

        • ArrayList vs LinkedList: Internals: resizable array (1.5x growth) vs doubly linked nodes (revisit Section 4 Lists), Big-O table for get, add, insert in middle, remove, Why ArrayList usually wins in practice (cache locality), Collection hierarchy question: List vs Set vs Queue vs Map, Traps: remove(int) vs remove(Object), Arrays.asList fixed size, List.of immutable
        • How HashMap Works Inside: put/get walkthrough: hashCode, hash spreading, bucket index (revisit Section 4 Maps, Section 6 Hash Tables from Scratch), Collisions: linked list and treeification (Java 8, threshold 8), Load factor 0.75, capacity, resizing and rehashing, null key handling; why keys should be immutable, Model answer to deliver in two minutes, plus follow-ups
        • HashMap vs TreeMap vs LinkedHashMap (and ConcurrentHashMap): Ordering, complexity and null rules comparison table, LinkedHashMap access order and an LRU cache in a few lines, TreeMap navigation: floorKey, ceilingKey, headMap, HashMap vs Hashtable vs ConcurrentHashMap in one minute (revisit Section 10 Concurrent Collections), Choosing the right map for a given requirement
        • HashSet Internals and Duplicates: HashSet is backed by a HashMap with a dummy value, How duplicates are detected: hashCode then equals, HashSet vs LinkedHashSet vs TreeSet, Predict the output: set of custom objects with and without equals/hashCode, Coding question: remove duplicates while keeping order
        • Comparable vs Comparator: Natural order vs external order (revisit Section 4 Sorting & Comparing), Comparator.comparing, thenComparing, reversed, Coding question: sort employees by salary desc then name, Trap: subtraction comparator overflow; compareTo inconsistent with equals in TreeSet
        • Fail-Fast Iterators and ConcurrentModificationException: modCount and why the exception is thrown, Predict the output: removing inside a for-each loop, Safe removal: Iterator.remove, removeIf, Fail-fast vs fail-safe (CopyOnWriteArrayList, ConcurrentHashMap), Trap: the 'second-to-last element' case that does not throw
        • Generics, Type Erasure and Wildcards: Why generics: type safety and no casts (revisit Section 4 Generics), Type erasure: what remains at runtime; why new T() and List<int> fail, Wildcards: ? extends vs ? super and PECS, Why List<Integer> is not a List<Number>, Writing a generic method with a bounded type
        • Practice: Collections & Generics Drill: Which-collection-would-you-use scenarios, Predict the output: maps, sets and iterators, Coding questions: word frequency, first non-repeating character, group anagrams, Explain-the-internals round: HashMap, HashSet, ArrayList growth
      • Output Prediction & Debugging Rounds

        • Operator, Division and Overflow Puzzles: How to trace: write variable values line by line (revisit Section 1 Operators, Section 3 OOP Mastery & Code Tracing), i++ + ++i, compound assignment implicit casts (byte b += 1), Integer division, % with negatives, char + int, string + number order, Overflow: Integer.MAX_VALUE + 1, int multiplication before widening to long, Floating-point: 0.1 + 0.2, == on doubles
        • String and == Puzzles: Compile-time constant folding vs runtime concatenation with ==, final String variables and the pool, Predict the output: replace, substring, toUpperCase without assignment, Wrapper == puzzles mixed with strings, Systematic checklist for any string puzzle
        • Static, Overriding and Hiding Puzzles: Static method hiding vs instance overriding with a parent reference, Field hiding: fields are not polymorphic, Constructor calling an overridden method: the default-value surprise, Initialization order: static blocks, instance blocks, constructors across parent and child, Static counter shared across instances
        • try, catch and finally Flow Puzzles: return in try and finally: which value wins, finally modifying a returned primitive vs object, Exception thrown in catch and in finally: what is lost, Nested try blocks and which catch runs, Unreachable catch compile errors
        • Finding, Explaining and Preventing the Bug: A method for reading unfamiliar code: inputs, outputs, edge cases (revisit Section 18 Debugging), Classic bugs: off-by-one, wrong loop bound, missing break, == on strings, NPE, integer overflow, Explaining the fix aloud: cause, fix, test that proves it, Prevention: unit tests, static analysis, code review habits, Worked examples of 5 short buggy methods
        • Practice: Output Prediction & Debugging Mock Test: Timed written-round set: 15 predict-the-output questions, Five find-the-bug methods with explain-the-fix answers, Scoring guide and review of the most-missed traps, Compile-error-or-output questions
      • DSA in Interviews

        • Clarifying Questions and Edge Cases: The first two minutes: restate the problem, confirm input/output (revisit Section 5 How to Approach a Problem), Standard clarifying questions: sizes, ranges, duplicates, sorted?, nulls, empty input, Listing edge cases before coding, Worked example on 'two sum' and 'longest substring'
        • Brute Force First, Then Improve: Why stating brute force earns credit, Optimization levers: hashing, sorting, two pointers, prefix sums, binary search (revisit Section 5 patterns), Talking through the trade-off as you improve, Worked example: pair sum from O(n^2) to O(n), When to stop optimizing
        • Stating Time and Space Complexity: Quick rules to read Big-O off loops, recursion and collection calls (revisit Section 5 Time & Space Complexity), Hidden costs: substring, contains on a list, string concatenation in loops, Space: auxiliary vs output, recursion stack, How to phrase it: 'O(n log n) time because of the sort, O(n) extra space for the map'
        • Coding on a Whiteboard or Paper in Offline Interviews: Step by step at the board: restate the problem, write 2 examples, agree the approach, then code, Board layout: function signature top-left, helpers on the side, space to fix lines; readable handwriting and naming, Writing Java without an IDE: exact syntax that matters (loops, array/list/map APIs, generics) and what interviewers forgive, Dry running on the board with a variable table, then testing edge cases out loud, Shared editor habits: no IDE autocomplete, compile mentally
        • Live Coding on a Shared Screen in Online Interviews: Before the call: Java and IDE ready, font size up, notifications off, camera, mic, internet backup, a blank Main.java template, Shared editors (CoderPad, HackerRank CodePair, CodeSignal-style pads, Google Docs) vs sharing your own IDE: what changes and what to ask first, Step by step during the round: confirm the question, think aloud, type small pieces, run often with your own test inputs in main, When it breaks: reading compiler and runtime errors aloud, debugging with prints calmly, asking for a hint well, Etiquette and proctoring: share only the needed window, no copy-paste from outside, what to do if the connection drops
        • Frequently Asked Problem Types by Data Structure: Arrays/strings, hashing, two pointers, sliding window: the fresher favourites, Linked lists, stacks/queues, trees, graphs, heaps: classic question list, DP and recursion questions at product companies, Where to practise each in Section 7 Coding Challenges, Pattern-recognition cues from the problem statement
        • Practice: DSA Mock Coding Round: Three timed problems (easy, medium, medium) with full interview narration, Model transcript: clarify, brute force, optimize, code, dry run, complexity, Self-score rubric for communication and correctness, Follow-up variants interviewers add
      • Streams & Modern Java Questions

        • Intermediate vs Terminal Operations and Laziness: Recap: source, intermediate, terminal (revisit Section 8 Stream Basics), Predict the output: peek with no terminal operation; short-circuiting with findFirst, Streams cannot be reused: IllegalStateException, Collection vs Stream; parallel streams in one minute, Traps: side effects in map, modifying the source
        • map vs flatMap, groupingBy and Collectors: map vs flatMap with a list-of-lists example (revisit Section 8 Transforming Streams, Collectors), groupingBy with counting, mapping and summing, toMap and the duplicate key exception, partitioningBy, joining, reduce vs collect
        • Optional: Correct and Incorrect Use: Why Optional exists (revisit Section 8 Optional), orElse vs orElseGet: the eager-evaluation trap, Anti-patterns: get() without check, Optional fields and parameters, map/flatMap/ifPresentOrElse chains, Model answer: 'Should a method return null or Optional?'
        • Functional Interfaces, Lambdas and Method References: Function, Predicate, Consumer, Supplier, BiFunction in one table (revisit Section 8 Functional Interfaces in Practice), @FunctionalInterface rules; default methods allowed, Four kinds of method references with examples, Effectively final variables in lambdas, Lambda vs anonymous class: this and scope
        • Date and Time API Questions: Why java.time replaced Date/Calendar (revisit Section 8 Date & Time API), LocalDate, LocalDateTime, ZonedDateTime, Instant: when to use each, Period vs Duration; formatting and parsing with DateTimeFormatter, Coding question: age from birth date, days between dates, Traps: immutability (plusDays without assignment), months 1-based
        • Practice: Write-the-Stream Coding Questions: Classic stream questions: second highest salary, frequency map, duplicates, first non-repeated char, Group employees by department and average salary, Convert a loop to a stream and back, Predict-the-output set on laziness and Optional
      • Multithreading & JVM Questions

        • Thread vs Runnable vs Callable: Recap: creating threads (revisit Section 10 Thread Basics), start() vs run(): predict the output, Thread lifecycle states; sleep vs wait; join, Callable and Future: returning values and exceptions, Process vs thread; daemon threads
        • synchronized, volatile and Race Conditions: Race condition demo: counter++ is not atomic (revisit Section 10 Race Conditions, Visibility & volatile), synchronized methods vs blocks; object vs class lock, volatile: visibility not atomicity, AtomicInteger and when to use it, wait/notify and the producer-consumer question
        • Deadlock: Cause and Prevention: Write a two-lock deadlock on demand (revisit Section 10 Classic Concurrency Bugs), Four necessary conditions, Prevention: lock ordering, tryLock with timeout, Detecting with a thread dump (jstack) in one line, Livelock and starvation definitions
        • Executors and Thread Pools: Why pools: cost of threads (revisit Section 10 Executors & Thread Pools), Fixed, cached, single, scheduled executors; ThreadPoolExecutor parameters, submit vs execute; shutdown vs shutdownNow, CompletableFuture and ConcurrentHashMap one-minute answers, Trap: forgetting shutdown, unbounded queues
        • Stack vs Heap and Class Loading: JVM memory areas: stack, heap, metaspace, PC register (revisit Section 11 JVM Memory Areas), Where locals, objects and static fields live: draw it, StackOverflowError vs OutOfMemoryError, Class loaders: bootstrap, platform, application; delegation model (revisit Section 11 Class Loading), JIT in one line
        • Garbage Collection and Memory Leaks: Reachability and GC roots; generational heap (revisit Section 11 Garbage Collection Basics), Can you force GC? System.gc(); finalize deprecated, Collectors in one line: Serial, Parallel, G1, ZGC, Memory leaks in Java: static collections, unclosed resources, listeners, Strong, weak, soft references
        • Practice: Concurrency & JVM Drill: Rapid-fire concurrency and JVM questions, Fix three buggy concurrent snippets, Write a producer-consumer with BlockingQueue, Explain-the-diagram: memory areas for a given program
      • Backend, Spring & Database Questions

        • SQL and Database Design Questions: Join types, WHERE vs HAVING, GROUP BY (revisit Section 12 Joins, Aggregates & Grouping), Classic queries: second highest salary, duplicates, Nth highest with window functions, Normalisation 1NF-3NF and primary vs foreign keys in one minute, Indexes: what they speed up and cost; ACID and isolation levels, DELETE vs TRUNCATE vs DROP
        • JDBC, PreparedStatement and SQL Injection: JDBC steps in order (revisit Section 13), Statement vs PreparedStatement; how injection works with ' OR '1'='1, try-with-resources for Connection/ResultSet; connection pooling in one line, Transactions: setAutoCommit(false), commit, rollback, DAO pattern question
        • REST Principles, HTTP Methods and Status Codes: REST constraints and resource naming (revisit Section 14 REST API Design), GET/POST/PUT/PATCH/DELETE; safe and idempotent methods, Status codes asked: 200, 201, 204, 400, 401, 403, 404, 409, 500, PUT vs PATCH, path vs query parameters, stateless and sessions, Design question: endpoints for a ShopLite order
        • Dependency Injection, Beans and Spring Boot: IoC and DI; constructor vs field injection (revisit Section 15 Dependency Injection & Beans), @Component vs @Service vs @Repository vs @Controller; @Bean, Bean scopes and lifecycle; @Autowired with multiple beans (@Qualifier, @Primary), How auto-configuration works: starters, @SpringBootApplication, conditions, @RestController vs @Controller; @ControllerAdvice; profiles
        • JPA Entities, Lazy Loading and the N+1 Problem: JPA vs Hibernate vs Spring Data JPA (revisit Section 16), Entity lifecycle and persistence context; save vs saveAndFlush, Lazy vs eager; LazyInitializationException, N+1 problem and fixes: join fetch, entity graph, @Transactional: propagation basics and self-invocation trap
        • Authentication, JWT and Password Hashing: Authentication vs authorisation; 401 vs 403 (revisit Section 17), Why hash passwords with BCrypt, not encrypt; salting, JWT structure, signing, expiry; stateless auth flow, Spring Security filter chain in one minute; CORS and CSRF questions, Traps: storing secrets in JWT payload, no expiry
        • Testing, Design Patterns and Basic System Design Questions: Unit vs integration tests; JUnit 5 and Mockito in one minute (revisit Section 18), Patterns asked of freshers: Singleton (thread-safe), Factory, Builder, Strategy, Observer (full coverage in Section 19), Patterns inside Spring: proxy, template, singleton beans, Basic system design answers: caching, load balancing, scaling a database (interview angle only; classic questions in Section 21), How to answer 'design a URL shortener' at fresher level: pointer to Section 21 Classic Design Questions
        • Practice: Java Backend Interview Drill: Rapid-fire Spring, JPA, REST and security questions, Write three SQL queries on the ShopLite schema, Spot the problem: N+1 in a service method, field injection, SQL concatenation, Walk through a request from controller to database aloud
      • Talking About Your Projects

        • A Short Project Pitch: Problem, Solution, Your Role: 60-second and 3-minute pitch templates, Worked pitch for ShopLite and for a Section 22 project, Stating your role honestly in a team project, Numbers that help: endpoints, tables, tests, users
        • Explaining Your Design and Tech Choices: Architecture walk-through: layers, database, auth (revisit Section 15 Layered Architecture), Answering 'why Spring Boot / MySQL / JWT?' with trade-offs, 'What would you change?' and 'how would it scale?' answers, Drawing your design on paper in two minutes
        • Challenges You Solved and Did-You-Build-It Questions: STAR format for a technical challenge story, Example stories: a bug you debugged, a performance fix, a design change, Probing questions: 'show me where X happens', 'what if this input is null?', Red flags interviewers notice in copied projects
        • Linking Answers to Your GitHub Code: A README that sells the project: setup, features, screenshots, API list (revisit Section 2 GitHub & Teamwork), Clean commit history and meaningful messages, Pinning projects and keeping the resume link working, Navigating your repo live during an interview
        • Practice: Project Explanation Mock: Record and review your 60-second pitch, Answer 15 probing project questions, Peer-review checklist for clarity and honesty, Turn one weak answer into a strong STAR story
      • Mock Technical Interviews

        • Mock Round: Core Java, OOP and DSA (Stage 1-2): 45-minute script: intro, core Java and OOP theory, predict-the-output, one coding problem, Interviewer questions with model answers revealed after you try, Coding problem with expected narration and solution, Scoring rubric per section, Live-coding part done twice: once on a shared screen, once on paper, timed
        • Mock Round: Java Backend Role: 60-minute script: project walk-through, Spring/JPA/REST/SQL questions, code review snippet, one coding problem, Follow-up chains interviewers use to go deeper, Model answers and a scoring rubric, Optional basic design question with pointer to Section 21
        • Self-Review Checklist and Common Rejection Reasons: Self-review checklist: accuracy, structure, communication, code quality, time, Common rejection reasons: weak fundamentals, silent coding, not knowing own project, bluffing, Turning feedback into a fix list, Behaviour during the round: asking for hints, handling nerves
        • A Revision Plan for the Last Week Before Interviews: Day-by-day plan: core Java, OOP, collections, output puzzles, DSA patterns, project, mock, One-page cheat sheets to build and revise, What not to do: learning new frameworks the night before, Interview-day checklist: resume copies, setup for online rounds, questions to ask the interviewer
    2. Placement Assessments & Career Preparation

      Aptitude and reasoning, core CS subjects (OS, DBMS, computer networks), resume, HR interviews and communication.

      • Placement Process & Test Formats

        • How campus and off-campus hiring works: Campus drives, pool drives and off-campus applications: who runs each and how you register, Service companies vs product companies: common differences in volume, rounds and roles (hedged, varies by year), Typical pipeline: eligibility filter, online test, technical round(s), HR round, offer letter, Eligibility criteria you will meet: CGPA cut-offs, backlogs, year gaps, branch rules, Timeline from registration to joining date and what happens in between
        • Online test sections and how they are scored: Common sections: quantitative, logical, verbal, technical MCQs, coding, sometimes a written email/essay, Adaptive vs fixed tests and what that means for skipping, Raw score, percentile and sectional scores explained with a worked example, How question counts and time per section translate to seconds per question, Reading the instructions screen: navigation, review flags, section locks
        • Negative marking, sectional cut-offs and time management: Expected value of guessing with +1/-0.25 and +1/-0.33 marking: worked numbers, When eliminating two options makes a guess worth it, Sectional cut-offs: why one weak section can fail the whole test, Two-pass strategy: attempt easy questions first, mark and return, Tracking the clock: checkpoints at 25%, 50% and 75% of section time
        • Rules and conduct in online proctored tests: How proctoring works: webcam, microphone, screen sharing, tab-switch detection (common features, platform-dependent), System check before the test: browser, internet backup, power, quiet room, ID ready, What counts as malpractice and why it can cost you every drive, not just one, What to do if the test freezes or the network drops: screenshots, contacting support, TPO, Honest conduct: no outside help, phones away, single screen
        • Online coding assessments: format and Java setup: HackerRank/HackerEarth-style problems: statement, constraints, sample input/output, hidden test cases, Reading input fast in Java 17: Scanner vs BufferedReader with StringTokenizer, single-file Main class, Printing exactly the expected output: spaces, newlines, no extra prompts, Partial scoring, time limit exceeded and wrong answer: what each verdict means and how to react, Reading constraints to pick the complexity: n up to 10^5 means O(n log n) or better
        • Coding-round time management and common problem patterns: Splitting 60-90 minutes across 2-3 problems: read all first, solve easiest first, Common patterns in fresher coding rounds: arrays, strings, hashing, sorting, simple greedy, prefix sums, Brute force first for partial marks, then optimise if time allows, Testing with sample and your own edge cases (empty, one element, max values) before submitting, Worked example: a frequency-count problem solved in Java with an O(n) HashMap approach
        • Building your placement preparation timetable: Mapping weeks to topics: aptitude, reasoning, verbal, coding, core CS, resume and HR, Daily routine for students with classes: 60-90 minute blocks and weekend mocks, Tracking accuracy and time per topic in a simple sheet, Choosing free and paid practice resources without overbuying, Adjusting the plan after each mock based on weak areas
        • Practice: test strategy drill: Calculate guess value for five negative-marking schemes, Plan time budgets for three sample test patterns, Spot rule violations in proctored-test scenarios, Fix a Java coding submission that fails on input reading and output format, Draft your own 8-week timetable
      • Operating Systems

        • Processes, threads, process states and context switching: What an OS does: resource manager, kernel vs user mode, system calls, Process vs thread: memory, cost, communication, Process states and the PCB, Context switching and its cost, Interview questions with model answers
        • CPU scheduling: FCFS and SJF: Terms: arrival, burst, waiting, turnaround and response time, FCFS with a Gantt chart and the convoy effect, SJF and SRTF with worked averages, Preemptive vs non-preemptive scheduling, Worked numeric example with exact averages
        • CPU scheduling: Round Robin, priority and multilevel queues: Round Robin with a time quantum: worked example, Choosing the quantum: too small vs too large, Priority scheduling, starvation and aging, Multilevel and multilevel feedback queues, Interview questions with model answers
        • Synchronisation, critical sections and semaphores: Race condition example and the critical-section problem, Mutual exclusion, progress and bounded waiting, Mutex vs binary vs counting semaphore, Producer-consumer and readers-writers at a high level, Interview questions with model answers
        • Deadlock: conditions, prevention and avoidance: The four Coffman conditions with a real-life example, Resource allocation graphs, Prevention vs avoidance vs detection and recovery, Banker's algorithm worked example (safe sequence), Deadlock vs starvation
        • Memory management: paging and segmentation: Contiguous allocation, internal and external fragmentation, Paging: pages, frames, page table, worked address translation, TLB and effective access time, Segmentation and how it differs from paging, Interview questions with model answers
        • Virtual memory and page replacement algorithms: Virtual memory, demand paging and page faults, FIFO on a worked reference string, and Belady's anomaly, Optimal and LRU on the same reference string, Thrashing and the working set, Counting page faults with exact answers
        • File systems and basic Linux concepts: Files, directories, inodes and allocation methods, Disk scheduling at a glance (FCFS, SSTF, SCAN), Linux basics: kernel, shell, permissions (chmod 755), processes (ps, kill), Common Linux commands asked in interviews, Interview questions with model answers
        • Practice: OS rapid-fire and numericals: 20 rapid-fire OS questions with short answers, Scheduling and page-fault numericals, Deadlock scenario analysis, Fix wrong model answers, Self-scoring sheet
      • DBMS

        • DBMS vs file system and types of keys: Problems with file systems: redundancy, inconsistency, concurrency, Three-level architecture and data independence, Super, candidate, primary, alternate, foreign and composite keys, Worked example identifying keys in a table, Interview questions with model answers
        • ER diagrams: Entities and attributes (simple, composite, multivalued, derived), Relationships and cardinality (1:1, 1:N, M:N), Weak entities and participation, Converting an ER diagram to tables, Worked example: a college placement system
        • Normalisation: functional dependencies, 1NF and 2NF: Insert, update and delete anomalies, Functional dependencies and attribute closure, 1NF: atomic values, 2NF: removing partial dependencies, Worked decomposition example
        • Normalisation: 3NF and BCNF: Transitive dependencies and 3NF, BCNF and how it differs from 3NF, Lossless join and dependency preservation, Denormalisation and when it is used, Worked decomposition example
        • ACID properties, transactions and concurrency: ACID with a bank-transfer example, Transaction states, commit and rollback, Dirty read, non-repeatable read and phantom read, Isolation levels and serializability at a high level, Locks and deadlock in databases
        • Indexing basics: Why indexes speed up reads and slow down writes, Clustered vs non-clustered indexes, B-tree and B+ tree at interview level, When an index is not used, Interview questions with model answers
        • SQL vs NoSQL at a high level: Relational vs document, key-value, column and graph stores, Schema flexibility and vertical vs horizontal scaling, The CAP theorem in simple terms, When to pick each, with examples, Interview questions with model answers
        • Classic SQL interview queries: Nth highest salary: LIMIT/OFFSET, correlated subquery and DENSE_RANK, Finding and deleting duplicate rows, Employees earning more than their manager (self join), Department-wise max salary and counts with GROUP BY/HAVING, Second highest without LIMIT; DELETE vs TRUNCATE vs DROP
        • Practice: DBMS mixed round and SQL drill: 20 rapid-fire DBMS questions, Normalise two tables, Write 6 interview SQL queries, Fix wrong queries, Self-scoring sheet
      • Computer Networks

        • OSI and TCP/IP models: The seven OSI layers with a mnemonic and one job each, The TCP/IP four-layer model and its mapping to OSI, Encapsulation: data, segment, packet, frame, bits, Which devices and protocols work at each layer, Interview questions with model answers
        • IP addresses and subnetting basics: IPv4 structure, classes and private ranges, CIDR notation and subnet masks, Worked subnetting: hosts per subnet, network and broadcast address, IPv4 vs IPv6, Practice set with exact answers
        • MAC addresses, ARP, DHCP and NAT: MAC address vs IP address, ARP: finding a MAC from an IP, DHCP: how a device gets an IP, NAT and why a home network shares one public IP, Interview questions with model answers
        • TCP vs UDP and the three-way handshake: Connection-oriented vs connectionless, Three-way handshake and four-way termination, Reliability: sequence numbers, ACKs, retransmission, Flow control vs congestion control, When UDP fits: video calls, DNS, games
        • DNS and what happens when you type a URL: DNS hierarchy: resolver, root, TLD, authoritative server, DNS caching and record types (A, AAAA, CNAME, MX), The full URL journey: DNS, TCP, TLS, HTTP request, response, rendering, Model answer to "what happens when you type a URL", Follow-up questions interviewers ask
        • HTTP vs HTTPS, ports and common protocols: HTTP methods and status codes at a glance, HTTPS and TLS: certificates and encryption at a high level, Common ports: 20/21, 22, 25, 53, 80, 443, 3306, FTP, SMTP, SSH and other application protocols, HTTP/1.1 vs HTTP/2 at a glance
        • Routers, switches and basic network security: Hub vs switch vs router vs gateway, LAN, WAN and VLAN basics, Firewalls, VPNs and proxies, Common attacks: DoS, man-in-the-middle, phishing, Interview questions with model answers
        • Practice: networks rapid-fire and subnetting drill: 20 rapid-fire networking questions, Subnetting numericals with exact answers, Explain the URL journey in two minutes, Fix wrong model answers, Self-scoring sheet
      • Resume & Online Profiles

        • One-page resume structure for freshers: Section order: header, education, skills, projects, internships, achievements, Header essentials: name, phone, professional email, LinkedIn, GitHub, Education formatting: CGPA, year, percentages, Fonts, margins and length; what to leave out (photo, DOB, generic objective), Full sample fresher resume template
        • Writing project and internship points with impact: Formula: action verb + what you built + tech + result, Before/after rewrites of weak bullet points, Quantifying honestly (users, records, response time), Describing a ShopLite-style Java project in three bullets, Never claiming work you cannot explain in an interview
        • Skills section: what to include and what to leave out: Grouping skills: languages, frameworks, databases, tools, Listing only skills you can be questioned on, Avoiding skill bars and percentage ratings, Certifications and coursework: when they help, Matching skills to a job description
        • Making your resume readable by screening software: How applicant tracking systems commonly parse resumes (general behaviour, varies by tool), Simple layouts: avoiding tables, images and columns that may break parsing, Using job-description keywords honestly, File naming, and PDF vs DOCX, The plain-text copy test
        • LinkedIn profile: headline, about and projects: Headline formula with examples, About-section template for a Java fresher, Featured and projects sections linked to GitHub, Connecting with alumni and recruiters politely, with a sample message, Keeping the profile consistent with the resume
        • Making your GitHub profile match your resume: Profile README template, Pinning the projects listed on your resume, A good project README: what it does, tech, setup, screenshots, Clean commit history and no committed secrets, Archiving half-finished repositories
        • Practice: resume review drill: Spot problems in three sample resumes, Rewrite ten weak bullet points, Match a resume to a job description, Review a sample GitHub and LinkedIn profile, Peer-review checklist
        • Project: build your resume, LinkedIn and GitHub portfolio: Write your one-page resume from the template, Add your ShopLite project with three impact bullets, Publish a GitHub profile README and pin projects with READMEs, Update LinkedIn headline, about and featured items, Self-check against the ATS and honesty checklists
      • HR & Behavioural Interviews

        • Tell me about yourself: Present-past-future structure in 60-90 seconds, Model answers for a CS fresher and a non-CS-branch fresher, What not to say: reciting the resume, family details, memorised scripts, Adapting the answer for service vs product companies, Practising aloud and timing yourself
        • Strengths, weaknesses and why this company: Strength with evidence: claim plus example, A real weakness plus what you are doing about it, Researching the company honestly: website, products, news, Model answers and weak answers compared, Where do you see yourself in five years
        • STAR method for behavioural questions: Situation, Task, Action, Result explained, Building a story bank from projects, college events and internships, Model STAR answers: team conflict, failure, tight deadline, leadership, Keeping answers honest and under two minutes, Handling follow-up questions
        • Relocation, bonds, shifts and higher-studies questions: Answering relocation and night-shift questions honestly, Service agreements and bonds: what to read before signing (terms vary by company), Higher-studies plans: honest answers that do not hurt your chances, Gaps, backlogs and branch questions, Model answers for each
        • Salary discussions and evaluating fresher offers: Reading CTC: fixed pay, variable pay, joining bonus, benefits, Worked example: approximate monthly in-hand pay from a CTC breakdown (PF, professional tax, income tax, hedged), When freshers can and cannot negotiate, Comparing two offers: role, learning, location, bond, growth, Offer etiquette and college placement policies (rules vary by college)
        • Questions to ask the interviewer: Why asking questions matters, Good questions about role, team, training and growth, Questions to avoid in early rounds, Closing the interview and thanking the panel, Follow-up email after the interview
        • Practice: HR question drill: 20 common HR questions answered in your own words, Improve three weak sample answers, Record and review a two-minute STAR answer, Offer comparison exercise, Self-review checklist
      • Group Discussion & Communication

        • How group discussions are evaluated: GD formats: topic-based, case-based, abstract, What evaluators commonly look for: content, communication, teamwork, leadership, Preparing content: current affairs and technology topics, Typical mistakes: shouting, silence, going off topic, Sample GD topics for freshers
        • Starting, adding to and summarising a discussion: Ways to start: definition, fact, question, quote, Adding value: a new point, an example, data, Bringing in quiet members, Summarising at the end in 30 seconds, Annotated model GD transcript
        • Handling disagreement politely: Polite phrases to disagree, Acknowledge, then counter with evidence, Handling a dominating participant, Staying calm and respectful, Practice scenarios
        • Clear spoken English: pace, structure and filler words: Point-reason-example structure for answers, Pace, pauses and clear pronunciation, Reducing filler words (um, like, basically), Explaining a technical project simply, Daily speaking practice routine
        • Body language and online interview etiquette: Posture, eye contact and hand gestures, Online setup: camera at eye level, lighting, background, audio, Joining on time, muting and handling tech issues, Dress code for campus and online interviews, Checklist before an online interview
        • Professional email writing: Subject lines that say what the email is about, Templates for emails to the TPO, recruiters and HR, Following up, rescheduling, accepting and declining offers, Tone, length and signatures, Common mistakes and corrected versions
        • Practice: GD and communication drill: Prepare points for five GD topics, Annotate a sample GD for strong and weak contributions, Record a two-minute talk and count filler words, Write three placement emails, Self-review checklist
      • Mock Placement Rounds

        • Mock online coding assessment: Two timed problems solved as single-file Java 17 programs reading stdin, Sample and hidden-style test cases, Model solutions with complexity notes, Reviewing what partial scores tell you, Coding-round checklist
        • Core CS rapid-fire round: 30 mixed OS, DBMS and networks questions with short model answers, Answering in two or three sentences, Saying "I am not sure" honestly and reasoning aloud, Scoring sheet, Topics to revise based on misses
        • Mock HR interview with self-review: Ten-question HR mock script, Recording yourself or practising with a friend, Self-review checklist: structure, honesty, length, body language, Improving answers after review, Second-attempt comparison
        • Mock group discussion: Ten mock GD topics with key points, Running a GD with friends: roles and timer, Peer feedback form, Common improvements after the first mock, Plan for the second round
        • Final revision plan before placement season: Last four weeks: revision schedule by topic, Formula and concept sheets to keep, Mock-test schedule and rest, Document checklist: resume copies, ID, mark sheets, Mindset on placement day and handling rejection

From your first program to job-ready

Python roadmap

One clear route for students and job seekers: learn Python, crack coding rounds, know your core subjects, build resume projects and prepare for interviews.

Choose your route

Python developer roadmap for beginners: the stages

  1. Stage 1: Learn Python

    Build your programming foundation

    • Python Basics
    • Developer Setup
    • Git & GitHub
    • Git in Practice
    • Python OOP
    • Python Collections & Data Structures
    See this stage
    See all topics in Learn Python
    1. Python Basics

      Variables, dynamic typing, operators, input and output, conditions, loops, functions, lists, strings, dictionaries, sets and exceptions, ending with mini projects.

    2. Developer Setup

      Work like a developer from day one: the terminal, virtual environments (venv) and pip.

    3. Git & GitHub

      Git version control and GitHub, shared by every MentorNxt course: commits, branches, merge conflicts, pull requests with code review, forks and issues.

      • Git Basics

      • Branches & Merging

        • Branches: create one and switch to it: A branch is a movable label, What HEAD is, git branch, switch and switch -c, Switching with uncommitted changes
        • Merging branches: Fast-forward vs merge commit, Three-way merges and the merge base, Deleting merged branches: -d vs -D, Merging main into a feature branch
        • Merge conflicts: Why conflicts happen, Reading conflict markers, Resolving in the editor and the IDE merge tool, Finishing or aborting a merge
        • Common mistakes and practice: The feature branch loop, A commit on the wrong branch, Detached HEAD, A merge blocked by local changes
      • GitHub & Teamwork

        • Put your project on GitHub: Git vs GitHub, public vs private, git remote add and push -u, Signing in with a token or SSH, Cloning, and first-push errors
        • Clone, push, pull and fetch: origin/main: Git's saved copy of the remote, Ahead, behind and diverged, Fetch vs pull, A rejected push and why not to force it
        • Write a README in Markdown: Markdown syntax, What a good README has, Your GitHub profile README, Choosing a licence
        • Pull requests and code review: The feature branch workflow, A clear pull request description, Reviewing and replying with new commits, Updating with main, merging and cleaning up
        • Forks, issues and open source: Fork vs clone, The upstream remote and syncing a fork, Issues and good bug reports, Closing issues from pull requests
        • Common mistakes and practice: Unrelated histories after 'Add a README', 'Everything up-to-date' with uncommitted work, Conflicts during pull, What to do about a leaked secret
    4. Git in Practice

      Put Git and GitHub to work on your own Python project: keep junk and secrets out, list your packages and write a README others can run.

    5. Python OOP

      Classes, constructors, encapsulation, inheritance, polymorphism, dunder methods, properties and dataclasses, ending with mini projects.

    6. Python Collections & Data Structures

      Lists, tuples, sets, dictionaries, comprehensions, deque, Counter, defaultdict, and heapq: how each works inside and choosing the right one.

  2. Stage 2: Master DSA

    Become a confident problem solver

    • Problem Solving & Coding Patterns
    • Data Structures & Algorithms in Python
    See this stage
    See all topics in Master DSA
    1. Problem Solving & Coding Patterns

      A repeatable way to solve problems.

    2. Data Structures & Algorithms in Python

      The structures and algorithms interviews expect.

  3. Stage 3: Core CS & SQL

    Answer the theory rounds with confidence

    • Core CS Subjects
    • SQL & Database Design
    See this stage
    See all topics in Core CS & SQL
    1. Core CS Subjects

      The theory asked in technical interviews.

    2. SQL & Database Design

      Store and query data the way real applications do.

  4. Stage 5: Get Job Ready

    Prepare for your first software job

    • Python Technical Interview Preparation
    • Placement Assessments & Career Preparation
    See this stage
    See all topics in Get Job Ready
    1. Python Technical Interview Preparation

      The questions interviewers really ask.

    2. Placement Assessments & Career Preparation

      Show your work and get through the process.

  5. Stage 6: Master Python

    Develop strong core Python skills

    • Idiomatic Python
    • Regex, Dates & Logging
    • Concurrency & AsyncIO
    • Python Internals & Performance
    See this stage
    See all topics in Master Python
    1. Idiomatic Python

      The language features you meet in every real Python codebase.

    2. Regex, Dates & Logging

      The standard library tools every developer needs: regular expressions, dates and logging.

    3. Concurrency & AsyncIO

      Do many things at once, and choose the right tool for the job.

    4. Python Internals & Performance

      What really happens when your code runs.

  6. Stage 7: Build Applications

    Become a Python backend developer

    • SQLAlchemy & Migrations
    • Web Fundamentals, HTTP & REST APIs
    • FastAPI
    • Authentication & Security
    See this stage
    See all topics in Build Applications
    1. SQLAlchemy & Migrations

      Work with your database from Python.

    2. Web Fundamentals, HTTP & REST APIs

      How the web works, and how to design a good API.

    3. FastAPI

      Build fast, documented APIs.

    4. Authentication & Security

      Protect your users and your data.