Module 2: Java Fundamentals, Variables & Data Types
Java Variables & Scope (Local, Instance, Static)
Understand how to declare variables, constants with final, and the lifecycle of Local, Instance, and Static variables.
a variable is declared determines its **scope** (where it can be accessed), **lifetime** (when it is created and destroyed), **memory region** (Stack vs Heap vs Metaspace), and **default value**.
Declare, initialize, and update variables and `final` constants.
Distinguish between **Local**, **Instance**, and **Static (Class)** variables in memory and lifecycle.
| Inside a method, constructor, or block | Thread Stack | **None** (compile error if read before init) | Until the method/block exits |
Module 2: Java Fundamentals, Variables & Data Types
Java Data Types & Type Casting
Explore all 8 primitive data types (byte, short, int, long, float, double, char, boolean), non-primitive types, literals, and implicit/explicit type casting.
**Widening (Implicit)**: Converting a smaller type to a larger type happens automatically with no data loss: `byte -> short -> int -> long -> float -> double` (and `char -> int`).
**Narrowing (Explicit)**: Converting a larger type to a smaller type requires an explicit cast `(targetType)` and may truncate decimals or overflow!
**Numeric Promotion in Expressions**: Arithmetic on `byte`, `short`, or `char` automatically promotes operands to `int`. That is why `byte a = 10, b = 20; byte c = (byte)(a + b);` requires a cast.
**Logical (`&&`, `||`, `!`)**: Use **short-circuit evaluation**: in `a != null && a.length() > 0`, if `a != null` is `false`, Java skips evaluating the right-hand side completely, preventing a `NullPointerException`.
Declare, initialize, and traverse 1D, 2D, and jagged arrays, and understand fixed-size heap allocation.
**Multidimensional & Jagged Arrays**: A 2D array `int[][]` is actually an array of references to 1D `int[]` arrays on the Heap. Therefore, each row can have a **different length** (a **Jagged Array**).
Reuse and specialize classes using single, multilevel, and hierarchical inheritance, invoke parent constructors with super(), and prefer composition when appropriate.
**Single**: `B extends A`
**Multilevel**: `C extends B extends A`
**Hierarchical**: `B extends A` and `C extends A`
**Multiple Inheritance**: Disallowed for classes (prevents the **Diamond Problem**, where two parent classes define conflicting implementations of the same method), but supported for **interfaces** (`class X implements A, B`).
Hide implementation complexity with abstract classes and interfaces, implement multiple interfaces, and use Java 8+ default/static interface methods.
**`default` methods (Java 8+)**: Allow adding new methods to interfaces without breaking existing implementations.
**`@FunctionalInterface`**: Marks an interface with **exactly one abstract method** so it can be implemented concisely via a Lambda expression or Method Reference.
Master private fields, validated getters/setters, all 4 Java access levels, user-defined packages, and import statements.
(no keyword) | Yes | Yes | No | No |
**Packages** (`package com.codezov.service;`) mirror directory structure, prevent class name collisions, and enable package-private encapsulation.
**Static Imports** (`import static java.lang.Math.PI;`) let you reference static constants/methods without qualifying the class name (use sparingly to keep code readable).
Object Class, Wrapper Classes, Records & Sealed Classes
Override toString, equals, and hashCode properly, use Wrapper classes & autoboxing, and leverage modern Java Records and Sealed classes.
**`toString()`**: Returns a human-readable string representation (default is `ClassName@hexHash`). Always override it on domain models for clear logs and debugger inspection.
**`equals(Object o)`**: Must be reflexive, symmetric, transitive, consistent, and return `false` for `null`.
**`hashCode()`**: Must return the **same integer** for any two objects where `a.equals(b)` is `true`. If you override `equals()` without overriding `hashCode()`, two equal objects may land in different `HashMap` buckets and never be found!
Perform mathematical operations with Math.pow, Math.sqrt, Math.abs, rounding methods, and generate pseudo-random and cryptographically secure numbers.
**`java.util.Random`**: Uses a 48-bit seed and a Linear Congruential Generator (LCG). It is fast and deterministic (given the same seed, it reproduces the exact same sequence—great for unit tests and simulations), but **predictable**. An attacker observing a few outputs can deduce the seed and predict future numbers.
**`java.security.SecureRandom`**: Gathers entropy from the OS kernel (`/dev/urandom` or Windows CryptGenRandom). Always use `SecureRandom` for OTPs, password reset tokens, API keys, and cryptographic salts.
Handle runtime failures gracefully using try-catch, multi-catch, try-with-resources (AutoCloseable), custom exceptions, and best practices.
**`Error`**: Severe JVM/system failures (`OutOfMemoryError`, `StackOverflowError`, `NoClassDefFoundError`). Applications generally cannot recover from these and should not catch them.
**`Exception`**:
* **Checked Exceptions** (`IOException`, `SQLException`, `ClassNotFoundException`): Verified at compile time; the caller **must** either handle them with `try-catch` or declare `throws` in the method signature.
Use java.util.regex.Pattern and Matcher for pattern matching, quantifiers, groups, and email/phone validation.
**`Pattern.compile(regex)`**: Compiles the regex string into an internal finite-state automaton. **Always** compile patterns once into a `static final` constant—calling `String.matches(regex)` inside a loop recompiles the regex on every iteration!
**`Matcher`**: Stateful matching engine created by `pattern.matcher(input)`:
Master the Java Collections hierarchy, dynamic resizing in ArrayList, doubly-linked nodes in LinkedList, and ArrayDeque/PriorityQueue.
**`ArrayDeque`**: Resizable circular array implementing both Queue (FIFO) and Stack (LIFO). Faster than legacy `Stack` (which is synchronized) and `LinkedList`.
**`PriorityQueue`**: Binary min-heap supporting O(log n) `offer()` / `poll()` and O(1) `peek()`—ideal for top-K problems and task scheduling.
Generic Classes, Methods, Wildcards & Type Erasure
Achieve compile-time type safety with generics, PECS wildcards (? extends / ? super), and understand JVM type erasure.
**Upper-Bounded (`? extends T`)**: Use when the collection **produces** `T` values for you to read (`List<? extends Number>`). You cannot add elements (except `null`) because the exact subtype is unknown.
**Lower-Bounded (`? super T`)**: Use when the collection **consumes** `T` values you write into it (`List<? super Integer>`).
**Unbounded (`?`)**: Use when you only need `Object` methods or `List.size()`.
Understand java.io byte vs character streams, buffering for performance, and closing streams automatically with try-with-resources.
**Byte Streams (`InputStream`, `OutputStream`)**: Read and write raw 8-bit bytes (`0–255`). Always use these for binary files (images, PDFs, ZIP archives, audio).
**Character Streams (`Reader`, `Writer`)**: Read and write 16-bit Unicode characters and handle character encoding/decoding automatically. Always specify `StandardCharsets.UTF_8` explicitly instead of relying on the OS default charset.
Understand Java serialization, excluding sensitive fields with transient, and versioning classes with serialVersionUID.
**`Serializable`**: A marker interface (no methods). If a `Serializable` class holds a reference to a non-serializable field, serialization throws `NotSerializableException` unless that field is marked `transient`.
**`serialVersionUID`**: Always declare `private static final long serialVersionUID = 1L;`. If omitted, the JVM computes a hash from class structure—meaning adding a single method breaks deserialization of previously saved objects with `InvalidClassException`.
**`transient` & `static`**: Both `transient` fields and `static` fields are skipped during serialization.
**Security Warning**: Never deserialize untrusted byte streams from external users (deserialization gadget attacks); prefer JSON (Jackson/Gson) or Protobuf for APIs.
Create threads using Runnable/Thread, understand thread states, avoid calling run() directly, and scale with ExecutorService and CompletableFuture.
is an independent OS program with its own isolated virtual address space. A **thread** is a lightweight unit of execution *inside* a process: all threads in a JVM share the **Heap** and **Metaspace**, while each thread maintains its own private **JVM Stack** and **Program Counter (PC) Register**.
from the *execution mechanism* lets you submit tasks to thread pools.
Calling `t.start()` asks the JVM to allocate a new call stack and schedule concurrent execution.
Calling `t.run()` directly is a common bug—it simply executes synchronously on the current thread! Calling `t.start()` twice throws `IllegalThreadStateException`.
Ensure thread safety using synchronized methods/blocks, ReentrantLock, AtomicInteger, volatile visibility, and deadlock prevention.
**`wait()`, `notify()`, `notifyAll()`**: Must be called inside a `synchronized` block on the lock object. Always call `wait()` inside a `while (!condition)` loop (not `if`) to guard against **spurious wakeups**.
**Deadlock Prevention**: A deadlock occurs when Thread A holds Lock 1 waiting for Lock 2 while Thread B holds Lock 2 waiting for Lock 1. Break circular wait by **always acquiring locks in a consistent global order** or using `ReentrantLock.tryLock()`.
Build secure database-driven Java applications with Connection, PreparedStatement (preventing SQL injection), ResultSet, and ACID transactions.
**JDBC Driver (Type 4 Pure Java)**: Translates JDBC calls into the database's native wire protocol (e.g., `mysql-connector-j`).
**`DriverManager` vs `DataSource`**: `DriverManager.getConnection(...)` opens a raw TCP connection per call (slow). Production servers always use a **`DataSource` connection pool** (like **HikariCP**) to reuse open connections.
**`PreparedStatement` vs `Statement`**: Never concatenate user input into SQL strings with `Statement`—that causes **SQL Injection**! `PreparedStatement` precompiles parameterized SQL (`?` placeholders) and binds user values safely as literal data.
**`ResultSet`**: Forward-only cursor over query rows (`while (rs.next())`).
Format currencies, numbers, and dates for global audiences using Locale and NumberFormat.
**`Locale`**: Represents a language + region pair (e.g., `en-IN`, `en-US`, `fr-FR`).
**`ResourceBundle`**: Loads locale-specific `.properties` files (`messages_en.properties`, `messages_hi.properties`) with automatic fallback to the base bundle.
**`NumberFormat` & `DateTimeFormatter`**: Format numbers, percentages, currencies, and dates according to regional grouping and symbols.
**Young Generation (Eden + Survivor S0/S1)**: Fast **Minor GC** sweeps short-lived objects in milliseconds.
**Old (Tenured) Generation**: Objects that survive multiple Minor GCs are promoted here and collected by **Major / Mixed GC**.
**Modern Collectors**: **G1GC** (default since Java 9, balances throughput and pause times) and **ZGC** (Generational ZGC in Java 21 achieves sub-millisecond pauses on multi-GB/TB heaps).
Version-Wise Modern Java Features (Java 5 through Java 25)
Accurately map every landmark Java feature to the exact JDK version that introduced it—from Java 5 Generics to Java 21 Virtual Threads.
releases every 2 years (Java 8, 11, 17, 21, 25). Knowing **which version introduced each feature** prevents compatibility bugs and is frequently tested in senior Java interviews.
Servlets, JSP, Sessions & Spring Boot Introduction
Understand HTTP request/response lifecycles in Servlets & JSP, session management, and how Spring Boot simplifies enterprise REST APIs.
**Servlet Lifecycle**: Container calls `init()` once -> `service(HttpServletRequest, HttpServletResponse)` dispatches `doGet`/`doPost` per HTTP request -> `destroy()` on shutdown.
**JSP**: HTML templates with embedded directives/expressions that the container compiles into Servlets.
**Sessions & Cookies**: HTTP is stateless; `HttpSession` stores server-side session state keyed by a `JSESSIONID` cookie, whereas modern REST APIs typically use stateless signed **JWT** tokens.
**IoC & Dependency Injection**: Spring's `ApplicationContext` instantiates and wires `@RestController`, `@Service`, and `@Repository` beans via constructor injection, decoupling components for easy testing.
Capstone Project: Console Banking & Student Management System
Build a complete OOP-based Banking & Student Management application with encapsulated accounts, collections, exception handling, and transaction history.