Java Tutorial
Core Java, OOP, collections, concurrency and modern Java features.
Start learning →482 lessons · 2256 min total
1Introduction to Java
- What Is JavaWhat Java is, what people build with it, and how one Java program runs on Windows, macOS and Linux without any changes.easy7 min
- History of JavaHow Java began as the Oak project at Sun Microsystems in 1991, how it got its name, and how it reached Java 25 today.easy6 min
- Features of JavaThe main features of Java, such as platform independence, object orientation, safety and multithreading, explained with examples.easy7 min
- Java Versions and Release CycleHow Java versions are numbered, why a new version comes out every six months, and what LTS means for the version you should use.easy7 min
- Java Editions (SE, Jakarta EE, ME)The difference between Java SE, Jakarta EE (formerly Java EE) and Java ME, and which one you need to learn first.easy5 min
- JDK DistributionsWhy there are many JDKs (Oracle JDK, Eclipse Temurin, Amazon Corretto and more), how they differ, and which one to install.easy5 min
- Difference Between C++ and JavaHow Java differs from C++ in compilation, memory management, pointers, inheritance and typical uses, with side-by-side code.easy6 min
- Difference Between Java and Python / JavaScriptHow Java compares with Python and JavaScript in typing, speed, syntax and typical jobs, with the same program in all three languages.easy5 min
- Where Java Is UsedWhere Java is used in the real world, from UPI and banking servers to Android apps and big data, and the jobs that use it.easy5 min
2Setup, First Program and Debugging
- Installing the JDKHow to install JDK 25 on Windows, macOS and Linux, check that it works, and fix the most common installation problems.easy6 min
- How to Set PATH and JAVA_HOMEWhat the PATH and JAVA_HOME variables do, how to check them, and how to set them on Windows, macOS and Linux so the right Java runs.easy5 min
- Java Hello World ProgramWrite, compile and run your first Java program, understand each line at a first-day level, and fix the two mistakes almost everyone makes.easy5 min
- What Happens When a Java Program RunsWhat javac does at compile time and what the JVM does at runtime: class loading, bytecode verification, the interpreter and the JIT compiler.easy6 min
- The Main Method in JavaWhat each word in public static void main(String[] args) means, how to pass command-line arguments, and the main method questions interviewers ask.easy5 min
- Compiling and Running from the Command LineUse javac and java from a terminal: compile one or many files, keep .class files apart with -d, run them with -cp, and read launcher errors.easy5 min
- Running a Single Source File DirectlyRun a .java file in one step with java File.java, use other source files in the same folder (Java 22+), and turn a Java file into a script on macOS and Linux.easy5 min
- Compact Source Files and Instance Main MethodsJava 25 lets you write a program as just void main() { ... } with the IO class for input and output. What it removes, what it adds, and when to use it.easy5 min
- JShell (Interactive Java)Try Java one line at a time with JShell: expressions, variables, methods, the most useful commands, and when a scratch pad beats a full program.easy4 min
- Choosing an IDEIntelliJ IDEA, Eclipse and VS Code compared for learning Java: what an IDE does for you, which one to pick, and the shortcuts worth learning on day one.easy5 min
- Using the DebuggerFind bugs by pausing your program and watching it run: breakpoints, step over, step into, step out, watches and conditional breakpoints, with a real bug to fix.easy6 min
- Common Beginner Compile ErrorsHow to read a javac error message, and how to fix the eight compile errors every beginner meets, from ';' expected to missing return statement.easy6 min
3Java Architecture
- Difference Between JDK, JRE and JVMWhat the JDK, the JRE and the JVM each contain, how they fit inside one another, which one you install, and how to answer this classic interview question.easy7 min
- JVM: The Java Virtual MachineWhat the JVM really is (a specification, an implementation such as HotSpot, and a running process), what it does for you, and other languages that use it.easy6 min
- JVM Architecture OverviewThe three parts of the JVM: the class loader subsystem, the runtime memory areas (heap, stacks, method area) and the execution engine, with what each one does.medium8 min
- Bytecode and Platform IndependenceWhat bytecode is, what's inside a .class file, how to read it with javap, what class file versions mean, and where platform independence stops.easy7 min
- JIT CompilerHow the JVM's just-in-time compiler makes Java fast: hot code, tiered compilation with C1 and C2, warm-up, and how to watch it work with PrintCompilation.medium6 min
4Java Language Basics
- Java KeywordsThe 51 reserved words of Java 25 grouped by what they do, the contextual keywords such as var and record, and why true, false and null are not keywords.easy5 min
- Identifiers and Rules for NamingWhat an identifier is in Java, the five rules every name must follow, which names fail to compile, and how case sensitivity trips up beginners.easy4 min
- Java Naming ConventionsThe naming style every Java team uses: PascalCase for classes, camelCase for methods and variables, UPPER_SNAKE_CASE for constants and lowercase for packages.easy4 min
- Java CommentsSingle-line, multi-line and documentation comments, how javadoc turns comments into HTML, and what makes a comment worth writing.easy5 min
- Java VariablesWhat a variable is, how to declare and assign one, and the three kinds in Java: local, instance and static, with where each lives and how long it lasts.easy6 min
- Scope and Lifetime of VariablesWhere a variable can be used (its scope) and how long it exists (its lifetime): block scope, loop variables, method scope, fields, and shadowing.easy5 min
- Constants in JavaLock values with final: final locals, static final constants in UPPER_SNAKE_CASE, and why a final reference can still change its object.easy5 min
- Data Types in JavaJava's eight primitive types with their sizes and ranges, reference types such as String and arrays, how each is stored, and how to choose the right type.easy6 min
- Default Values of Data TypesWhich variables Java fills with default values (fields and array elements), what those defaults are for each type, and why local variables get none.easy4 min
- Unicode System in JavaWhy Java uses Unicode, how a char stores one UTF-16 code unit, how to write Unicode escapes, and why emoji take two chars.easy5 min
- Literals in JavaEvery kind of Java literal: integers in four bases, underscores like 1_00_000, L and f suffixes, chars, strings, text blocks, booleans and null.easy5 min
- Type Casting and Type ConversionWidening conversions Java does for you, narrowing casts you must write, what narrowing loses (decimals, overflow), and char to int casts.easy5 min
- Type Promotion in ExpressionsThe rules Java uses to pick the type of an expression: byte, short and char become int, the widest operand wins, and why byte + byte doesn't fit back in a byte.easy5 min
- Integer Overflow and Floating-Point PrecisionWhy Integer.MAX_VALUE + 1 becomes negative, why 0.1 + 0.2 isn't 0.3, how to detect overflow with Math.addExact, and how to handle money correctly.medium5 min
- Local Variable Type InferenceHow var lets the compiler work out a local variable's type, where you can and can't use it, the diamond trap, and when var makes code clearer or worse.easy4 min
- Java OperatorsThe families of operators in Java: arithmetic, relational, logical, assignment, bitwise and shift, with what each one does and the result type it produces.easy5 min
- Ternary OperatorThe ternary operator condition ? a : b: how it picks one of two values, when it reads better than if-else, the type of its result, and why nesting it hurts.easy4 min
- Increment and Decrement OperatorsHow ++ and -- work, the difference between pre-increment (++x) and post-increment (x++), how to predict tricky expressions, and the classic interview puzzles.easy5 min
- Short-Circuit EvaluationHow && and || stop as soon as the answer is known, how that protects null checks and expensive calls, and how & and | differ by always evaluating both sides.easy5 min
- Operator Precedence and AssociativityWhich operator runs first in Java: the precedence table, left and right associativity, evaluating expressions by hand, and when to add brackets.easy6 min
5Input and Output Basics
- Printing Output in JavaHow print, println and printf differ, where the cursor ends up after each, escape sequences for tabs, quotes and new lines, and printing several values.easy5 min
- Format SpecifiersHow printf and String.format build neat output: %d, %f, %s and %n, width, precision, flags, and the errors a wrong specifier causes.easy5 min
- Scanner ClassRead keyboard input with Scanner: next, nextInt and nextLine, how input is split into tokens, the nextInt-then-nextLine trap, and bad input.easy6 min
- Scanner vs BufferedReaderTwo ways to read console input: Scanner, which converts types for you, and BufferedReader, which reads whole lines fast. When to choose which.easy4 min
- Simple Console I/O with the IO ClassJava 25's java.lang.IO class: println, print and readln for quick console programs without System.out or Scanner, what readln returns, and when to use it.easy4 min
- Command Line ArgumentsPass values to a program when you start it: how the command line becomes args, quoting values with spaces, converting and checking them.easy4 min
6Control Statements
- Control Statements in JavaAn overview of how Java decides what to run next: decision statements (if, switch), loops (for, while, do-while) and jump statements (break, continue, return).easy4 min
- Java If-Else StatementsMake decisions with if, if-else, the else-if ladder and nested if: how each form works, how the order of conditions matters, and the dangling-else trap.easy5 min
- Switch StatementChoose between many fixed values with switch: case labels for int, char, String and enum, why break matters, fall-through and default.easy5 min
- Switch ExpressionsThe modern switch that produces a value: arrow syntax, several labels per case, yield for multi-line cases, and exhaustiveness checks.easy4 min
- Java for LoopRepeat code a known number of times with the for loop: its four parts, the exact order they run in, counting up, down and in steps, and off-by-one mistakes.easy5 min
- Java For-Each LoopVisit every element of an array or list with the enhanced for loop: syntax, how it compares with a counting for loop, and what it can and can't do.easy4 min
- Java While LoopRepeat code while a condition stays true, when the number of rounds isn't known in advance: how while works, input loops, and loops that never end.easy4 min
- Java Do-While LoopThe loop that runs its body at least once: do-while syntax, how it differs from while, menus and input checks that suit it, and the semicolon it needs.easy4 min
- Nested LoopsA loop inside a loop: how the inner loop runs fully for each outer round, tables and grids, counting total rounds, and keeping it readable.easy4 min
- Infinite LoopsLoops that never end: the usual causes, how to stop a stuck program, and the intentional while (true) loop with break used in servers and menus.easy5 min
- Java Break StatementLeave a loop or a switch early with break: stopping a search when you find what you need, break inside switch, and how break behaves in nested loops.easy4 min
- Java Continue StatementSkip the rest of one loop round with continue: filtering items, how continue behaves in for, while and do-while loops, and when an if-else reads better.easy4 min
- Labeled Break and ContinueName a loop with a label so break can leave nested loops at once and continue can jump to the outer loop's next round, and when to use a method.easy4 min
- Java Return StatementEnd a method with return: returning values, early returns that check input first, return inside loops, and the missing return statement error.easy4 min
- Basic Java ProgramsClassic beginner programs with loops and conditions: star patterns, primes, factorial, Fibonacci, palindromes and Armstrong numbers.easy5 min
7Arrays
- Java ArraysStore many values of one type under one name: declaring, creating and initializing arrays, indexes from 0, default values, and memory layout.easy4 min
- Array LengthFind how many elements an array holds with length, why it's a field and not a method, the last valid index, empty arrays, and length vs length() vs size().easy3 min
- Traversing ArraysVisit every element of an array with a for loop or a for-each loop, go backwards or skip elements, find totals, maximums and positions, and pick the right loop.easy4 min
- Multidimensional ArraysTables and grids in Java with 2D arrays: creating them, row and column indexes, nested loops to traverse them, and why a 2D array is really an array of arrays.easy4 min
- Jagged Arrays2D arrays whose rows have different lengths: when they're useful, how to create each row separately, how to loop over them safely, and how they save memory.easy4 min
- Array of ObjectsArrays that hold objects: why a new array of objects is full of null, creating each object, looping over them, and the NullPointerException trap.easy4 min
- String ArraysArrays of text: creating String arrays, null vs empty strings, searching with equals, sorting, and splitting a line into words and joining them.easy3 min
- Passing Arrays to Methods and Returning ArraysPass an array to a method and get one back: why a method can change the caller's array, why it can't replace it, and how to return a new array safely.easy4 min
- Copying and Cloning ArraysWhy = doesn't copy an array, and the real ways to copy: a loop, Arrays.copyOf, Arrays.copyOfRange, System.arraycopy and clone, plus shallow vs deep copies.easy4 min
- Arrays ClassThe java.util.Arrays toolbox: toString, sort, binarySearch, fill, equals, copyOf and asList, with the traps in binarySearch and asList explained.easy4 min
- ArrayIndexOutOfBoundsExceptionThe most common array error: what triggers it, how to read its message, the off-by-one and empty-array cases that cause it, and how to prevent it.easy4 min
- Reverse an ArrayReverse an array in place with two pointers that swap toward the middle, why the loop runs half the length, and building a new reversed array.easy4 min
- Array ProgramsClassic array exercises with solutions: min, max and average, searching, removing duplicates, merging sorted arrays, and matrix addition.easy5 min
8Methods
- Methods in JavaBreak a program into named, reusable blocks: declaring and calling methods, parameters, return types and void, and why small methods help.easy4 min
- Method SignatureWhat a method signature is (name plus parameter types), what isn't part of it, how it tells overloaded methods apart, and clashing signatures.easy4 min
- Method Parameters and ArgumentsHow values travel into a method: parameters vs arguments, matching by position and type, widening, parameters as locals, and final parameters.easy4 min
- Static Methods vs Instance MethodsStatic methods, called on the class, vs instance methods, called on an object: what each can access, when to use which, and the static context error.easy5 min
- Call by Value and Call by Reference in JavaJava always passes by value: what that means for primitives and object references, why swap fails, and how a method can still change an object.easy5 min
- Varargs (Variable Arguments)Write methods that take any number of arguments with varargs (int... nums): how they become an array, the rules for using them, and where Java itself uses them.easy3 min
- Recursion in JavaA method that calls itself: base and recursive cases, how the call stack grows and unwinds, factorial and digit sum, and StackOverflowError.easy5 min
- Recursion vs IterationWhen to use a loop and when to use recursion: the same problems solved both ways, why naive recursive Fibonacci is slow, memory use, and how to choose.easy5 min
- Math ClassThe Math class toolbox: abs, max, pow, sqrt, round, floor, ceil, PI, floorDiv, floorMod and the exact methods, with the surprises in each.easy4 min
- Generating Random NumbersRandom numbers in Java: Math.random, Random with seeds, ThreadLocalRandom for ranges, SecureRandom for OTPs, and getting a range right.easy4 min
9OOP Fundamentals
- OOPs Concepts in JavaThe big picture of object-oriented programming: classes, objects, and the four pillars of encapsulation, inheritance, polymorphism and abstraction.easy5 min
- Procedural vs Object-Oriented ProgrammingThe same billing program written procedurally and with objects: where the data lives, who enforces the rules, and why OOP scales better as programs grow.easy5 min
- Classes and ObjectsHow to write a class with fields and methods, create objects from it with new, give each object its own state, and keep classes in their own files.easy5 min
- Difference Between Object and ClassClass vs object side by side: blueprint vs instance, loaded once vs created many times, where each lives in memory, and the classic interview answer.easy5 min
- Ways to Create Objects in JavaThe five ways to get an object: new, a factory method, reflection, clone() and deserialization, and which of them run a constructor.medium5 min
- Object References and NullWhat a reference variable holds, why assigning references shares one object, what null means, NullPointerException, and garbage.easy5 min
- Anonymous ObjectsObjects created and used in one expression without a variable: when they're handy, why you can't reuse them, and how they differ from anonymous classes.easy4 min
- Constructors in JavaConstructors set up a new object: the default constructor, no-arg and parameterized constructors, validation, and when the default disappears.easy5 min
- Constructor vs MethodConstructors and methods compared point by point: name, return type, when they run, how they're called, inheritance, and the void-constructor trap.easy4 min
- Constructor Overloading and Constructor ChainingGive a class several constructors, then chain them with this(...) so all setup and validation lives in one place. Also super(...), and the recursive-call error.medium4 min
- Private ConstructorsWhy you'd block new from outside: utility classes like Math, controlled creation with factory methods, and the singleton pattern.medium5 min
- Copy ConstructorCopy an existing object with a copy constructor: shallow vs deep copies, copying arrays and mutable fields safely, and why it beats clone().medium5 min
- Flexible Constructor BodiesJava 25 lets constructors run code before super(...) or this(...): validating arguments first, preparing values, and what is still forbidden.medium4 min
- Java This KeywordWhat this refers to, and its five uses: fields vs parameters, calling another constructor, passing and returning the current object.easy5 min
- Java Static KeywordWhat static means for variables, methods, blocks and imports: one copy per class, calling without an object, and what static code can't touch.medium5 min
- Instance Variable vs Static VariableInstance variables vs static variables side by side: one per object vs one per class, where each lives, when each is created, default values, and how to choose.easy4 min
- Instance Initializer BlockA block in braces that runs for every new object before the constructor body: when it runs, how constructors share it, and alternatives.medium4 min
- Static BlockCode that runs once when a class is initialized: static block syntax, setting up static data, when classes are initialized, and failures.medium4 min
- Order of InitializationThe exact order Java runs static blocks, instance blocks, field initializers and constructors, for parent and child classes, step by step.medium5 min
- Java Final KeywordThe three meanings of final: a variable that can't be reassigned, a method that can't be overridden, and a class that can't be extended.medium5 min
- Blank Final and Static Final VariablesFinal variables declared without a value: blank finals set in every constructor, blank static finals set in a static block, and the compile errors.medium4 min
10Inheritance
- Inheritance in JavaBuild a class on an existing one with extends: what a subclass inherits, adds or overrides, the is-a test, protected access, and Object.medium5 min
- Types of InheritanceSingle, multilevel and hierarchical inheritance with examples, why multiple and hybrid inheritance of classes aren't allowed, and how interfaces fill that gap.medium4 min
- The Diamond ProblemWhy Java has no multiple inheritance of classes: the diamond problem, clashing interface default methods, and resolving them explicitly.medium5 min
- Java Super KeywordThe three uses of super: calling the parent's constructor, calling the parent's version of an overridden method, and reaching a hidden field.medium4 min
- Constructor Calls in InheritanceHow constructors run in a hierarchy: the chain up to Object, the order bodies run in, the automatic super() call, and the no-arg error.medium4 min
- Aggregation in JavaModel a has-a relationship where the parts live on their own: a department that has employees, references as fields, and sharing parts.medium4 min
- Association, Aggregation and CompositionThree kinds of object relationship, loosest to strongest: association (uses), aggregation (has, can live apart) and composition (owns).medium5 min
- Composition vs InheritanceWhen to extend a class and when to hold one as a field: the is-a test, fragile base classes, a wrong extends refactored, and a checklist.medium5 min
- Upcasting and DowncastingTreat a child object as its parent type and back again: what the reference type allows, ClassCastException, and instanceof patterns.medium5 min
11Polymorphism
- Polymorphism in JavaOne call, many behaviors: what polymorphism means, its compile-time and runtime forms, and why it lets you add new types without changing old code.medium5 min
- Method Overloading in JavaSeveral methods with one name and different parameters: how the compiler picks one, the widening-boxing-varargs order, and ambiguous calls.medium6 min
- Method Overriding in JavaA subclass replaces an inherited method with its own version: how overriding works, @Override, reusing the parent with super, and a silent typo bug.medium4 min
- Rules of Method OverridingThe exact rules an overriding method must follow: signature, return type, access, checked exceptions, and which methods can't be overridden.medium6 min
- Method Overloading vs OverridingOverloading and overriding side by side: where each happens, who decides, the rules that differ, and the equals(Account) trap that mixes them up.medium5 min
- Can Static, Private and Final Methods Be OverriddenWhy static, private and final methods can't be overridden, what method hiding is, and why fields follow the variable's type instead of the object.medium6 min
- Covariant Return Type in JavaAn overriding method may return a subtype of the parent's return type. How it removes casts, its limits, and the bridge method the compiler adds.medium5 min
- Compile-Time Polymorphism in JavaCompile-time (static) polymorphism through overloading: how the compiler fixes the method before the program runs, shown in the bytecode.medium3 min
- Runtime Polymorphism and Dynamic Method DispatchHow the JVM picks an overriding method at runtime: the lookup from the object's class upward, a mixed Shape array, invokevirtual and method tables.medium6 min
- Static and Dynamic Binding in JavaBinding links a call to the code it runs. Which calls are bound at compile time, which at runtime, and the bytecode instructions that show it.medium5 min
- Java Instanceof and Pattern MatchingTest an object's type with instanceof, then let pattern matching declare the cast variable for you: binding variables, flow scoping and null.medium6 min
12Abstraction
- Abstraction in JavaShow what an object does and hide how it does it: abstraction with abstract classes and interfaces, and how it differs from encapsulation.medium5 min
- Abstract Classes and Abstract MethodsA partly built class: abstract methods subclasses must fill in, concrete shared code, constructors, the template method idea, and the compile errors.medium6 min
- Interfaces in JavaAn interface is a contract any class can sign: declaring and implementing one, implicit public abstract methods, constants, and interfaces as types.medium5 min
- Multiple Inheritance Through InterfacesA class can implement many interfaces and an interface can extend many: how Java gets multiple inheritance of type without the diamond problem.medium5 min
- Default, Static and Private Methods in InterfacesInterfaces with code: default methods that let interfaces grow, static helpers called on the interface, and private methods that share code inside it.medium6 min
- Diamond Problem with Default MethodsWhen a class inherits the same method from a class and interfaces: the three resolution rules, each shown running, plus the compile errors.medium5 min
- Marker Interfaces in JavaEmpty interfaces that tag a class: Serializable, Cloneable and RandomAccess, writing your own marker, and when an annotation is the better choice.medium4 min
- Difference Between Abstract Class and InterfaceAbstract class or interface? A full comparison, how to choose, and the skeletal-implementation pattern that uses both, the way the JDK does.medium6 min
- Difference Between Class and InterfaceA class is a complete blueprint for objects; an interface is a contract. Compare what each can contain, create and inherit, with one example using both.easy4 min
13Encapsulation and Packages
- Encapsulation in JavaKeep an object's data private and let methods guard every change. Why public fields break, how encapsulation enforces rules, and what it buys you.easy5 min
- Getters and Setters in JavaMethods that read and change private fields: naming rules, validation in setters, read-only fields, boolean is-getters, and safe getters for lists.easy5 min
- Data Hiding vs EncapsulationData hiding makes fields private; encapsulation also bundles the rules that protect them. A side-by-side example shows why hiding alone isn't enough.easy4 min
- Access Modifiers in Javaprivate, package-private, protected and public: who can reach a class, field or method, the protected subclass rule, and the errors across packages.medium5 min
- Packages in JavaPackages group related classes and give them unique names: built-in packages, writing your own, the folder layout, compiling with -d and running by full name.easy5 min
- Package Naming and Folder StructureHow to name packages (reverse domain, lowercase, no hyphens), how names map to folders, a standard project layout, and the errors when they don't match.easy3 min
- Import Statements in JavaUse classes from other packages by short name: single-type and wildcard imports, fully qualified names, name clashes, and what import does not do.easy4 min
- Static Import in JavaUse static fields and methods without the class name: import static syntax, good uses such as constants and test assertions, ambiguity, and overuse.easy3 min
- Classpath in JavaThe list of places where Java looks for classes: setting it with -cp, folders and JAR files, the search order, CLASSPATH, and class-not-found errors.medium5 min
- Module Import Declarations (Java 25)import module java.base; brings in every package a module exports in one line. How it works, resolving name clashes, and when to use it.medium4 min
14Object Class and OOP Misc
- Object Class in Javajava.lang.Object is the root of every class. Its 11 methods, what each is for, and why every object can be stored in an Object variable.medium4 min
- toString() Method in JavaGive objects a readable text form: the default ClassName@hash output, overriding toString, where Java calls it for you, and printing arrays.easy4 min
- Object Equality and Hash Codes in JavaDefine when two objects are equal, keep hashCode consistent with it, and see HashSet and HashMap break when the contract is violated.medium6 min
- getClass() Method in JavaFind an object's runtime class with getClass(): getName vs getSimpleName, class literals, comparing classes, and how it differs from instanceof.easy3 min
- Object Cloning in JavaCopy objects with clone(): the Cloneable marker, overriding clone correctly, shallow vs deep copies with a shared-array bug, and better alternatives.medium5 min
- Java Finalize Method (Deprecated)Why finalize() was meant for cleanup, why it never worked well, the removal warning in Java 25, and what to use instead: try-with-resources and Cleaner.medium5 min
- How to Create an Immutable Class in JavaObjects that can never change after creation: the rules for an immutable class, a Money example, why String is immutable, and the benefits.medium5 min
- Defensive Copying in JavaProtect an object's internals from callers: copy mutable inputs in constructors and outputs in getters, with lists, arrays and dates as examples.medium4 min
- Wrapper Classes in JavaInteger, Double, Character and friends: why each primitive has an object twin, when you need one, their constants and helper methods, and pitfalls.easy4 min
- Autoboxing and Unboxing in JavaJava converts between primitives and wrappers automatically. Where it happens, the valueOf and intValue calls it hides, and its NullPointerException traps.medium4 min
- Integer Cache in JavaWhy Integer 127 == 127 is true but 128 == 128 is false: the -128 to 127 cache behind valueOf, other wrapper caches, and the safe way to compare.medium4 min
- Integer.parseInt() vs Integer.valueOf()Convert text to numbers: parseInt returns an int, valueOf returns a cached Integer. Radix, signs, the NumberFormatException messages, and which to choose.easy4 min
- BigInteger and BigDecimal in JavaExact decimal money math with BigDecimal and unlimited whole numbers with BigInteger: creating them, rounding, comparing, and an immutable Money class.medium6 min
- Objects Utility Class in Javajava.util.Objects: null-safe equals and hashCode, requireNonNull for fail-fast checks, defaults for null values, and index checks, with examples.easy4 min
- Enums in JavaA fixed set of named constants as a real type: enums with fields, constructors and methods, constant-specific behavior, and enums implementing interfaces.medium5 min
- Enum Methods and Enums in Switchvalues(), valueOf(), ordinal(), name() and compareTo() on enums, the exception for unknown names, enums in switch, and what the compiler generates.medium5 min
- Coupling and Cohesion in JavaTwo measures of good design: low coupling between classes and high cohesion inside each. A tightly coupled order service refactored to depend on an interface.medium5 min
15Inner Classes
- Inner Classes in JavaClasses inside classes: the four kinds of nested class, what each can access, how to choose, and the Outer$Inner class files the compiler creates.medium5 min
- Member Inner Class in JavaA non-static class inside a class body: each object is tied to an outer object, reads its private fields, uses Outer.this, and can keep the outer alive.medium5 min
- Anonymous Inner Class in JavaDeclare and create a one-off class in a single expression: implementing interfaces, extending classes with arguments, the rules, and lambdas.medium5 min
- Local Inner Class in JavaA class declared inside a method: scope, capturing effectively final variables, local records, enums and interfaces, and when a local class beats a field.medium4 min
- Static Nested Class in JavaA static class inside another class: no outer object needed, how it differs from an inner class, typical uses like builders and Map.Entry, and errors.medium5 min
- Nested Interface in JavaInterfaces declared inside classes or interfaces: why they're implicitly static, how to implement and refer to them, and Map.Entry as the classic example.medium3 min
16Modern Data Types
- Records in JavaOne line declares an immutable data class: what a record generates, how to add methods, the rules, shallow immutability, and when to use one.medium5 min
- Compact Constructors in RecordsValidate, normalize and defensively copy record data in a compact constructor, add extra constructors with this(...), and avoid the common errors.medium4 min
- Sealed Classes and Interfaces in JavaControl exactly which classes may extend a type with sealed and permits, the final, sealed and non-sealed rule, and exhaustive switches with no default.medium6 min
17Object-Oriented Design
- SOLID Principles in JavaThe five SOLID design principles explained with Java examples, and a god-class order manager refactored into small classes that are easy to change.medium6 min
- Design Patterns in JavaAll 23 classic design patterns in plain English: what each one is for, an everyday comparison, and where Java itself uses it.medium8 min
- Creational Design PatternsThe five patterns for making objects: Singleton, Factory Method, Abstract Factory, Builder and Prototype, each explained simply with a runnable example.medium8 min
- Singleton Pattern in JavaGuarantee exactly one instance of a class: eager, lazy, holder and enum singletons, their thread-safety, how reflection breaks them, and when to avoid them.medium5 min
- Factory Pattern in JavaLet one place decide which class to create: static factory methods, a factory for discount policies by customer type, and factories in the JDK.medium4 min
- Builder Pattern in JavaCreate objects with many optional settings readably: the telescoping-constructor problem, a fluent static nested Builder, validation in build(), and records.medium4 min
- Structural Design PatternsThe seven patterns for fitting classes together: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy, each with a runnable example.medium10 min
- Behavioral Design PatternsThe eleven patterns for how objects share work, from Chain of Responsibility to Visitor, each explained with an everyday comparison and a runnable example.medium14 min
- Strategy Pattern in JavaSwap an algorithm at runtime by putting each version behind one interface: delivery-fee strategies, choosing one by name, Comparator, and lambdas.medium5 min
- Observer Pattern in JavaNotify many objects when one object changes: subjects and observers, subscribing and unsubscribing, an order-status example, and its pitfalls.medium5 min
18Strings
- Strings in JavaWhat a String really is, the ways to create one, and why Java keeps a String pool so identical text is stored only once.easy5 min
- String Literal vs New String ObjectWhy \"text\" and new String(\"text\") behave differently: where each object lives, how many objects are created, and which one to use.easy4 min
- Why String Is Immutable in JavaA String can never change after it's created. What that means in code, the five reasons Java's designers chose it, and its one cost.easy5 min
- String Intern Method in JavaWhat intern() does, how it returns the pooled copy of a string built at runtime, when it saves memory, and why everyday code rarely needs it.medium4 min
- String Comparison in JavaCompare strings correctly: == vs equals vs equalsIgnoreCase vs compareTo, why == fails, null-safe comparisons, and how sorting order is decided.easy4 min
- String Concatenation in JavaJoin strings with +, concat, String.join and StringBuilder. Left-to-right evaluation traps, null, and why + inside a loop is slow.easy5 min
- Substring in JavaCut out part of a string with substring(begin) and substring(begin, end): why the end index is excluded, real examples, and the errors.easy3 min
- String Methods in JavaThe String methods you'll use every day: length, charAt, indexOf, contains, replace, split, case changes and trimming, grouped by job.easy4 min
- Modern String Methods in JavaNewer String methods that save real effort: isBlank, strip, repeat, lines, formatted, indent and transform, and why strip beats trim.easy4 min
- Character Class Methods in JavaCheck and convert single characters with the Character class: letters, digits, case and white space, plus why char is secretly a number.easy3 min
- Converting Between String and Other TypesTurn text into numbers and booleans, and anything into text: parseInt, valueOf, toString, char arrays, number bases, and the errors to expect.easy4 min
- StringBuilder in JavaA changeable string for building text step by step: append, insert, delete, replace and reverse, how its buffer grows, and when to use it.easy5 min
- StringBuffer in JavaThe thread-safe, older twin of StringBuilder: the same methods, synchronized for multiple threads, and why new code rarely needs it.easy4 min
- Difference Between String and StringBufferString is fixed text; StringBuffer is changeable text. How they differ in mutability, equals, memory and speed, with a side-by-side example.easy3 min
- StringBuffer vs StringBuilderTwo changeable strings with one difference: StringBuffer is synchronized, StringBuilder is not. Which to choose, with a three-way comparison.easy4 min
- StringJoiner and String.join()Join many pieces with a separator, and optional brackets, without fiddling with the last comma: String.join, StringJoiner and setEmptyValue.easy3 min
- StringTokenizer Class (Legacy)The old way to split text into tokens: how StringTokenizer works, how it differs from split, and why new code should prefer split or Scanner.easy3 min
- Text Blocks in JavaWrite multi-line text with triple quotes: how Java removes the indentation, escapes you no longer need, line-joining with a backslash, and formatted().easy4 min
- String Formatting in JavaBuild neatly formatted text with String.format and formatted, reorder arguments, format for a locale, and show money, percentages and lakhs.easy3 min
- Character Encoding and Charsets in JavaHow text becomes bytes: Unicode, UTF-8 and other charsets, why mojibake like naïve appears, and how to always choose the charset explicitly.medium5 min
- How to Reverse a String in JavaFour ways to reverse a string: StringBuilder.reverse, a two-pointer swap, a backward loop and recursion, with what each costs and the emoji trap.easy4 min
- Java String Programs and FAQsTen string programs that interviews and college labs ask again and again, each solved and explained: palindromes, anagrams, frequency and more.medium6 min
19Regular Expressions
- Regular Expressions in JavaSearch text by pattern instead of exact words: Pattern and Matcher, find vs matches, positions and results, and why patterns are compiled once.medium5 min
- Regex Character Classes, Quantifiers and MetacharactersThe building blocks of a pattern: character classes, shortcuts like \\d and \\w, quantifiers, anchors, escaping, and greedy vs lazy matching.medium6 min
- Regex Groups and Named GroupsCapture parts of a match with parentheses: numbered and named groups, reusing them in replacements, non-capturing groups and back-references.medium4 min
- Regex with String MethodsUse regex straight from String: matches, split, replaceAll and replaceFirst, their surprises with dots and dollar signs, and when to precompile.medium3 min
- Validating Input with RegexReal validators for email, Indian phone numbers and strong passwords, a log-line parser with named groups, and how one bad pattern can freeze a server.medium6 min
20Exception Handling
- Exception Handling in JavaWhat an exception is, what happens when nobody handles one, and how try-catch lets a program recover from bad input and failures instead of crashing.easy5 min
- Exception Hierarchy in JavaThrowable, Error, Exception and RuntimeException: how Java's exception classes are organized, what each branch means, and why the tree matters.easy4 min
- Checked vs Unchecked ExceptionsWhy the compiler forces you to handle some exceptions and not others, the catch-or-declare rule, and how to decide which kind to use.medium5 min
- Common Exceptions in JavaThe runtime exceptions you'll meet most, from NullPointerException to ClassCastException: what causes each and how to prevent it.easy4 min
- Common Errors in JavaOutOfMemoryError and StackOverflowError: what fills the heap or the stack, how to reproduce both safely, and why you fix them instead of catching them.medium5 min
- Try-Catch Block in JavaHow try and catch work step by step, what the exception object tells you, how to handle and recover, and where the try block's variables live.easy4 min
- Multiple Catch Blocks and Multi-CatchHandle different exceptions differently with several catch blocks, why specific ones must come first, and how multi-catch shares one handler.easy5 min
- Nested Try Block in JavaA try inside another try: how an exception looks for the nearest matching catch, when nesting is useful, and how to keep it readable.easy4 min
- Finally Block in JavaCode that runs whether try succeeds, fails or returns: what finally is for, the order with return, the rare cases it doesn't run, and its traps.medium5 min
- Try-With-Resources in JavaOpen files and connections in the try header and Java closes them for you, in reverse order, even when something fails. Why it beats finally.medium5 min
- AutoCloseable vs CloseableTwo interfaces with one close() method: how they differ in exceptions and repeated calls, which JDK classes use each, and which your class should implement.medium4 min
- Suppressed Exceptions in JavaWhen closing a resource fails while another exception is already in flight: how try-with-resources keeps both, getSuppressed(), and addSuppressed().medium4 min
- Java Throw KeywordSignal a problem yourself with throw: validating arguments, choosing the right exception type, writing good messages, and rethrowing.easy4 min
- Java Throws KeywordDeclare which checked exceptions a method may pass to its caller with throws: when to declare instead of catch, and how declarations travel up.easy3 min
- Difference Between Throw and Throwsthrow raises one exception inside a method; throws declares what a method may pass on. A side-by-side comparison with one example using both.easy3 min
- Exception Propagation in JavaHow an uncaught exception travels back up the call stack, method by method, until a catch handles it or the program stops, with a step-by-step trace.medium5 min
- Reading a Stack Trace in JavaTurn the scary red error text into a map of the bug: the exception line, the frames from newest to oldest, your code vs library code, and Caused by.easy5 min
- Chained Exceptions in JavaWrap a low-level exception in a meaningful one without losing the original: the cause parameter, getCause, and turning checked exceptions into unchecked.medium4 min
- Exception Handling with Method OverridingWhat an overriding method may and may not declare in throws, why broader checked exceptions are forbidden, and the matching rule for constructors.medium5 min
- Custom Exceptions in JavaCreate your own exception classes: checked or unchecked, the constructors to provide, extra fields, and a number-parsing utility that ties it all together.medium5 min
- Difference Between Final, Finally and FinalizeThree similar words, three unrelated features: the final keyword, the finally block and the deprecated finalize() method, compared side by side.easy4 min
- Helpful NullPointerException MessagesSince Java 14, a NullPointerException says exactly which reference was null and what Java was trying to do. How to read the messages and get variable names.easy4 min
- Assertions in JavaCheck your own assumptions with assert: the syntax, why assertions are off unless you pass -ea, and when to use them instead of exceptions.easy4 min
- Exception Handling Best PracticesTwelve habits for exceptions that help instead of hurt: fail fast, catch specific types, never swallow, keep the cause, close with try-with-resources.medium5 min
21Generics
- Generics in JavaWhy generics exist: a list that accepts anything fails at runtime, a typed list fails at compile time. Type parameters, their names, and what you gain.medium5 min
- Generic Classes in JavaWrite your own generic class: declare a type parameter, use it in fields and methods, create typed instances, and use several parameters like Pair<K, V>.medium4 min
- Generic Interfaces in JavaInterfaces with type parameters: a Repository<T, ID> contract, implementing it with real types or keeping it generic, and the JDK's Comparable<T>.medium4 min
- Generic Methods in JavaA method with its own type parameter: the <T> before the return type, how the compiler infers T from the arguments, and when to give it explicitly.medium4 min
- Generic Constructors in JavaA constructor with its own type parameter, independent of the class: how to write one, when it's useful, and how it differs from a generic class.medium3 min
- Diamond Operator in JavaThe <> that saves repeating type arguments: how the compiler fills it in, using it with anonymous classes, and the trap of combining it with var.easy3 min
- Bounded Type Parameters in JavaRestrict a type parameter with extends so you can call its methods: T extends Number, T extends Comparable<T>, and multiple bounds with &.medium4 min
- Wildcards in Java GenericsWhy a List<Integer> isn't a List<Number>, and how ?, ? extends and ? super let one method accept many related list types safely.hard5 min
- PECS Rule in Java GenericsProducer extends, consumer super: a simple rule for choosing the right wildcard, explained with a copy method and the JDK's own Collections.copy.hard4 min
- Raw Types in JavaA generic type used without its <...>: why raw types still exist, the unchecked warnings they cause, the runtime crash they allow, and how to avoid them.medium3 min
- Type Erasure in JavaGenerics exist only at compile time: how the compiler checks types, erases them to Object or the bound, inserts casts, and what that means at runtime.hard4 min
- Bridge Methods in JavaHidden methods the compiler adds so overriding still works after type erasure: why compareTo(Object) appears in your class, and how to see it.hard4 min
- Heap Pollution and SafeVarargsWhen a variable of a generic type points to an object of the wrong type: how varargs and raw types cause it, the warnings, and when @SafeVarargs is honest.hard4 min
- Restrictions of Generics in JavaWhat you can't do with generics, why each rule exists because of type erasure, the exact compile errors, and the standard workaround for each.hard5 min
22Collections
- Collections in JavaThe Java Collections Framework is a set of interfaces and classes used to store and manage groups of objects. Learn its hierarchy and main types.medium5 min
- Collection Interface in JavaThe Collection interface is the root interface for lists, sets and queues. Learn its common methods, such as add, remove, contains, size and removeIf.easy4 min
- Iterable Interface in JavaThe Iterable interface allows an object to be used in a for-each loop. Learn its methods, how for-each uses it, and how to make your own class iterable.medium3 min
- Iterator and ListIterator in JavaIterator is used to traverse a collection and safely remove elements. ListIterator also moves backward and can add or replace elements in a list.medium5 min
- ConcurrentModificationException in JavaConcurrentModificationException is thrown when a collection is changed while it is being iterated. Learn why it happens, a surprising case, and four fixes.medium5 min
- Fail-Fast vs Fail-Safe IteratorsFail-fast iterators throw when a collection changes during iteration; fail-safe iterators work on a snapshot or tolerate changes. Learn both, with examples.medium4 min
- List Interface in JavaThe List interface represents an ordered collection that allows duplicates and access by index. Learn its methods, implementations and examples.easy4 min
- ArrayList in JavaArrayList is a resizable array that grows automatically. Learn how to create one, add, get, update, remove, search, sort and loop over its elements.easy4 min
- Difference Between Array and ArrayListArray vs ArrayList in Java: fixed vs dynamic size, primitives vs objects, length vs size(), performance, and when to use each, with examples.easy4 min
- ArrayList Internal WorkingHow ArrayList works inside: the internal array, default capacity of 10, growth by 1.5 times, copying on resize, and the cost of add, get and remove.medium5 min
- LinkedList in JavaLinkedList is a doubly linked list that implements both List and Deque. Learn its structure, methods and examples, and when it beats ArrayList.easy5 min
- Difference Between ArrayList and LinkedListArrayList vs LinkedList in Java: internal structure, speed of get, add and remove, memory use, and how to choose, with a timing example.easy5 min
- Vector in JavaVector is a legacy, synchronized resizable array that implements List. Learn its methods, how it grows, and why ArrayList replaced it.easy4 min
- Difference Between ArrayList and VectorArrayList vs Vector in Java: synchronization, performance, growth rate, legacy methods and iteration. Learn the differences and which one to use.easy3 min
- Stack Class in JavaThe Stack class is a last-in, first-out collection with push, pop, peek and search. Learn its methods, examples, and why ArrayDeque is preferred.easy4 min
- Comparable Interface in JavaThe Comparable interface gives a class its natural sorting order through compareTo. Learn its rules, examples and how sort and TreeSet use it.medium4 min
- Comparator Interface in JavaThe Comparator interface defines custom sort orders outside a class. Learn compare, lambdas, Comparator.comparing, reversed and nullsFirst, with examples.medium4 min
- Difference Between Comparable and ComparatorComparable vs Comparator in Java: natural vs custom order, compareTo vs compare, java.lang vs java.util, and when to use each, with one example.medium4 min
- Comparator Chaining in JavaComparator chaining sorts by several keys with thenComparing. Learn how ties are broken, how reversed works in a chain, and how to handle nulls.medium4 min
- Sorting Collections in JavaHow to sort lists, arrays, sets and maps in Java with Collections.sort, List.sort, Arrays.sort, TreeSet, TreeMap and streams, with examples.easy4 min
- Set Interface in JavaThe Set interface represents a collection with no duplicate elements. Learn its features, implementations, set operations and examples.easy4 min
- HashSet in JavaHashSet stores unique elements in a hash table with fast add, remove and contains. Learn its features, methods, ordering, and the equals and hashCode rule.easy4 min
- LinkedHashSet in JavaLinkedHashSet is a HashSet that remembers insertion order. Learn how it works, its methods, and when to choose it over HashSet and TreeSet.easy4 min
- SortedSet and NavigableSet in JavaSortedSet keeps elements sorted and NavigableSet adds closest-match searches. Learn first, last, headSet, tailSet, floor, ceiling and more.medium4 min
- TreeSet in JavaTreeSet stores unique elements in sorted order using a red-black tree. Learn its constructors, methods, custom ordering, and its rules about null.easy4 min
- EnumSet in JavaEnumSet is a very fast, compact Set for enum values. Learn how to create one with of, allOf, noneOf, range and complementOf, with examples.easy4 min
- Queue Interface and PriorityQueue in JavaThe Queue interface holds elements waiting to be processed, and PriorityQueue serves the smallest or most important first. Learn their methods with examples.medium5 min
- Deque Interface and ArrayDeque in JavaA Deque is a double-ended queue you can add to and remove from at both ends. Learn ArrayDeque as a queue and a stack, plus a playlist manager checkpoint.medium6 min
- Map Interface in JavaThe Map interface stores key-value pairs with unique keys. Learn its features, implementations, methods and examples of put, get, remove and containsKey.easy5 min
- Map.Entry and Iterating Over MapsMap.Entry represents one key-value pair. Learn every way to loop over a map: entrySet, keySet, values, forEach and iterators, plus removing while looping.easy4 min
- HashMap in JavaHashMap stores key-value pairs in a hash table for fast lookup. Learn its features, constructors, methods, ordering, and how to use your own classes as keys.easy5 min
- HashMap Internal WorkingHow HashMap works inside: hashCode, the bucket array, index calculation, collisions, linked lists and trees, load factor, resizing, and the get and put steps.hard9 min
- HashSet Internal WorkingHashSet is built on a HashMap: each element is stored as a key with a dummy value. Learn how add, contains and remove work inside, with a small rebuild.medium4 min
- Map Methods in JavaJava's modern Map methods: getOrDefault, putIfAbsent, computeIfAbsent, computeIfPresent, compute, merge, replaceAll and more, with a word-frequency counter.medium6 min
- LinkedHashMap in JavaLinkedHashMap is a HashMap that remembers insertion or access order. Learn its features, access-order mode, and how to build an LRU cache with it.medium5 min
- SortedMap and NavigableMap in JavaSortedMap keeps keys sorted and NavigableMap adds closest-key searches. Learn firstKey, headMap, tailMap, floorKey, ceilingEntry and more, with examples.medium4 min
- TreeMap in JavaTreeMap stores key-value pairs sorted by key using a red-black tree. Learn its constructors, methods, custom key order, and how it differs from HashMap.easy4 min
- Hashtable in JavaHashtable is a legacy, synchronized hash table map that allows no null keys or values. Learn its methods, how it differs, and what replaced it.easy3 min
- Difference Between HashMap and HashtableHashMap vs Hashtable in Java: synchronization, null handling, performance, iteration, legacy status and the modern ConcurrentHashMap alternative.easy3 min
- WeakHashMap and IdentityHashMap in JavaWeakHashMap drops entries whose keys are no longer used anywhere; IdentityHashMap compares keys with == instead of equals. Learn both, with examples.medium4 min
- EnumMap in JavaEnumMap is a fast, compact Map whose keys are values of one enum type. Learn its features, constructors and methods, with examples.easy3 min
- Properties Class in JavaThe Properties class stores string key-value settings and loads them from .properties files. Learn getProperty, setProperty, load, store and defaults.easy4 min
- Collections Class in JavaThe Collections class holds static helpers for collections: sort, reverse, shuffle, max, min, frequency, binarySearch and read-only or synchronized wrappers.easy4 min
- Arrays.asList vs List.ofArrays.asList and List.of both create lists quickly, but differ in mutability, null support and their link to the array. Learn every difference with examples.medium4 min
- Immutable Collections in JavaCreate unmodifiable lists, sets and maps with List.of, Set.of, Map.of, Map.ofEntries and copyOf. Learn their rules, benefits and common errors.easy4 min
- Unmodifiable vs Immutable CollectionsAn unmodifiable view blocks changes through itself but still shows changes to the original; an immutable collection never changes. Learn the difference.medium4 min
- Sequenced Collections in JavaJava 21 added SequencedCollection, SequencedSet and SequencedMap, with one set of methods for the first and last elements and a reversed view.easy4 min
- Synchronized vs Concurrent CollectionsSynchronized wrappers lock the whole collection; concurrent collections like ConcurrentHashMap let many threads work safely at once. Learn the difference.medium5 min
- Time Complexity of Collection OperationsBig O costs of add, get, remove and contains for ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue and ArrayDeque in one place.medium5 min
- Choosing the Right CollectionA step-by-step guide to picking the right Java collection: list, set, map, queue or deque, and which class, based on order, duplicates, lookups and threads.easy5 min
23Functional Programming
- Java 8 FeaturesJava 8 brought lambdas, functional interfaces, method references, streams, Optional, default methods and a new date and time API. Learn each with examples.easy4 min
- Lambda Expressions in JavaA lambda expression is a short, unnamed function you can pass as a value. Learn lambda syntax, parameters, bodies and where lambdas can be used.easy5 min
- Anonymous Class vs LambdaAnonymous classes and lambdas can both implement an interface inline. Learn the differences in syntax, this, state, interfaces supported and performance.medium4 min
- Effectively Final Variables and Lambda CaptureLambdas can use local variables only if they are effectively final. Learn what that means, why Java requires it, and the usual workarounds.medium5 min
- Functional Interfaces in JavaA functional interface has exactly one abstract method and can be implemented with a lambda. Learn the rules, @FunctionalInterface, and how to write your own.easy4 min
- Built-In Functional Interfaces in JavaThe java.util.function package: Predicate, Function, Consumer, Supplier, UnaryOperator, BinaryOperator and BiFunction, with their methods and examples.medium5 min
- Primitive Functional Interfaces in JavaIntPredicate, IntFunction, ToIntFunction, IntUnaryOperator and friends avoid boxing when lambdas work with int, long and double. Learn them with examples.medium4 min
- Composing Functions in JavaBuild bigger functions from small ones with andThen, compose, and, or, negate, Predicate.not and Function.identity. Learn each with examples.medium4 min
- Method References in JavaMethod references are a short form of lambdas that just call a method: String::length, System.out::println, ArrayList::new. Learn the four kinds.easy4 min
- How Lambdas Are CompiledLambdas don't become anonymous classes. Learn how javac turns them into private methods plus an invokedynamic call, and how LambdaMetafactory links them.hard5 min
- forEach Method in JavaThe forEach method runs a lambda for every element of a collection, map or stream. Learn Iterable.forEach, Map.forEach, Stream.forEach and their limits.easy3 min
- Stream API in JavaThe Stream API processes collections in pipelines of filter, map, sorted and collect. Learn what a stream is, its features, its parts and a first example.easy5 min
- Creating Streams in JavaWays to create a stream: from collections, arrays, Stream.of, ranges, iterate, generate, strings, files and builders, with examples of each.easy4 min
- Intermediate vs Terminal OperationsIntermediate stream operations return a new stream and are lazy; terminal operations produce a result and end the stream. Learn the full list of each.easy5 min
- Lazy Evaluation and Short-Circuiting in StreamsStreams process elements one at a time, only when needed, and can stop early. See the real order of operations, why infinite streams work, and the costs.hard5 min
- Stream Filter, Map and ReduceThe three core stream operations: filter keeps elements, map transforms them, and reduce combines them into one value. Learn each with examples.easy5 min
- Stream flatMap in JavaflatMap turns each element into a stream and joins them into one flat stream. Learn flatMap vs map, flattening lists, splitting words, and mapMulti.medium4 min
- Stream Sorted, Distinct, Limit and SkipShape a stream with sorted, distinct, limit, skip, takeWhile and dropWhile. Learn each operation, how they combine for paging, and common traps.easy4 min
- Primitive Streams in JavaIntStream, LongStream and DoubleStream work with numbers directly and add sum, average, max, range and summaryStatistics. Learn how and when to use them.easy4 min
- Collectors Class in JavaThe Collectors class supplies ready-made collectors for collect(): toList, toSet, toMap, joining, counting, summing, averaging, groupingBy and more.medium5 min
- groupingBy, partitioningBy, toMap and JoiningThe four most used collectors: group elements by a key, split them in two, build maps and join strings, with downstream collectors and examples.medium5 min
- Parallel Streams in JavaParallel streams split work across CPU cores using the common ForkJoinPool. Learn how they work, when they help, and when they are slower or wrong.hard5 min
- Stream Best Practices and Common MistakesWrite clear, correct streams: keep lambdas pure, avoid side effects, pick the right operation, know when a loop is better, plus a 10-question checkpoint.medium6 min
- Optional Class in JavaOptional is a container that may or may not hold a value, used to return 'no result' without null. Learn how to create, check, read and transform it.easy5 min
- Optional Best PracticesWhen to use Optional and when not to: return types yes, fields and parameters no, never null, no bare get, and how to chain map, flatMap and orElse well.medium4 min
- Base64 Encoding and Decoding in JavaEncode and decode data as Base64 text with java.util.Base64: basic, URL-safe and MIME encoders, padding, and why Base64 is not encryption.easy4 min
- Stream Gatherers in JavaGatherers, final in Java 24, add custom intermediate operations to streams: windowFixed, windowSliding, fold, scan and mapConcurrent, plus your own.hard4 min
24Date and Time
- Date and Calendar Classes in JavaThe legacy java.util.Date and Calendar classes: how they work, why they are confusing and error-prone, and why java.time replaced them in Java 8.easy4 min
- LocalDate, LocalTime and LocalDateTimeLocalDate holds a date, LocalTime a time, and LocalDateTime both, with no time zone. Learn how to create, read, change and compare them.easy5 min
- ZonedDateTime, ZoneId and InstantZonedDateTime is a date and time in a named time zone, ZoneId names the zone, and Instant is an exact moment in UTC. Learn them with a meeting scheduler.medium6 min
- Duration and Period in JavaDuration measures time in hours, minutes and seconds; Period measures dates in years, months and days. Learn both, plus an age calculator.easy5 min
- ChronoUnit and TemporalAdjustersChronoUnit counts and adds time in any unit, and TemporalAdjusters jump to dates like the last day of the month or next Monday. Learn both with examples.medium4 min
- DateTimeFormatter in JavaDateTimeFormatter formats dates and times as text and parses text back into dates. Learn built-in formats, patterns like dd-MM-yyyy, locales and parsing errors.easy4 min
- Converting Between Legacy and New Date ClassesConvert Date, Calendar, java.sql dates and TimeZone to and from Instant, LocalDate, ZonedDateTime and ZoneId with the bridge methods added in Java 8.medium4 min
25Utility Classes
- System Class in JavaThe System class gives access to the clock, system properties, environment variables, standard streams and array copying. Learn its main methods.easy4 min
- UUID Class in JavaUUID creates 128-bit universally unique identifiers. Learn randomUUID, nameUUIDFromBytes, fromString, versions, and when to use UUIDs as IDs.easy4 min
- Random and SecureRandom in JavaRandom makes fast, repeatable pseudo-random numbers; SecureRandom makes unpredictable ones for security. Learn their methods, streams and seeds.easy4 min
- NumberFormat and DecimalFormat in JavaFormat numbers as text with grouping, decimals, percentages and currencies using NumberFormat and DecimalFormat patterns, and parse them back.easy5 min
- ProcessBuilder in JavaProcessBuilder starts external programs from Java, sets their directory and environment, reads their output and waits for them to finish.medium4 min
26I/O Streams
- Java I/O StreamsJava I/O moves data in and out of a program through streams. Learn what a stream is, byte streams vs character streams, and the four base classes.easy5 min
- Java I/O Class HierarchyThe four abstract base classes of java.io, InputStream, OutputStream, Reader and Writer, their key methods, and the main subclasses of each.easy4 min
- File Streams in JavaFileInputStream, FileOutputStream, FileReader and FileWriter read and write files. Learn their constructors, append mode and character encodings.easy4 min
- Buffered Streams in JavaBuffered streams cut disk access by reading and writing in large blocks. Learn BufferedReader, BufferedWriter and friends, and measure the speed-up.medium5 min
- InputStreamReader and OutputStreamWriterInputStreamReader and OutputStreamWriter bridge byte streams and character streams using a charset. Learn how encodings work and why UTF-8 matters.medium4 min
- PrintStream and PrintWriter in JavaPrintStream and PrintWriter add print, println and printf to output streams. Learn their differences, error checking and writing reports to files.easy4 min
- DataInputStream and DataOutputStreamData streams read and write Java primitives and strings in a portable binary form. Learn writeInt, readDouble, writeUTF and the order rule.medium4 min
- ObjectInputStream and ObjectOutputStreamObject streams write whole Java objects to a stream and read them back. Learn writeObject and readObject, the Serializable requirement, and the risks.medium3 min
- In-Memory Streams in JavaByteArrayInputStream, ByteArrayOutputStream, StringReader, StringWriter, CharArrayReader and CharArrayWriter treat memory as a stream source or destination.easy4 min
- Console Class in JavaThe Console class reads lines and hidden passwords from the terminal. Learn readLine, readPassword, printf and why System.console() can be null.easy4 min
- The Decorator Pattern in Java I/Ojava.io adds features by wrapping streams inside other streams. Learn how the decorator pattern works there and how to write your own filter stream.hard5 min
- Specialized Streams ReferenceA reference to the less common java.io streams: SequenceInputStream, PushbackInputStream, PushbackReader, piped streams, filter streams and ObjectStreamField.medium4 min
27File Handling
- File Handling in JavaFile handling means creating, reading, writing and managing files. Learn the two Java APIs, java.io.File and NIO.2 Path and Files, and which to use.easy4 min
- NIO.2 Path and Files ClassesPath represents a file system location and Files performs operations on it. Learn how to build, join, normalize and inspect paths and the main Files methods.medium5 min
- Path vs File in Javajava.nio.file.Path vs java.io.File: error handling, features, symbolic links, performance and how to convert between them, with side-by-side examples.easy4 min
- How to Create a File in JavaCreate files in Java with Files.createFile, Files.createTempFile and File.createNewFile, and handle files that already exist or folders that are missing.easy3 min
- How to Write to a File in JavaWrite text and bytes to files with Files.writeString, Files.write, BufferedWriter and FileWriter, and control overwriting and appending with OpenOption.easy4 min
- How to Read a File in JavaRead files with Files.readString, readAllLines, lines and newBufferedReader. Learn which method suits small files, large files and binary data.easy4 min
- How to Delete, Copy and Move Files in JavaDelete, copy, move and rename files with Files.delete, deleteIfExists, copy and move, using options like REPLACE_EXISTING and ATOMIC_MOVE.easy3 min
- Working with Directories in JavaCreate, list, walk, search and delete folders with Files.createDirectories, list, walk, find and newDirectoryStream, including deleting a folder tree.medium4 min
- File Class in JavaThe legacy java.io.File class represents files and folders. Learn its constructors and methods, its silent-failure pitfalls, and converting to Path with toPath.easy4 min
- RandomAccessFile in JavaRandomAccessFile reads and writes anywhere in a file using a file pointer and seek. Learn its modes, methods, and how to update fixed-size records in place.medium4 min
- How to Create a Zip File in JavaCreate zip archives with ZipOutputStream and ZipEntry, compress files and folders, and build a tool that zips the largest files in a folder tree.medium4 min
- How to Read Files from a Zip File in JavaList and read the entries of a zip file with ZipFile and ZipInputStream, print their contents, extract them safely, and guard against zip slip.medium4 min
- Reading and Writing Properties FilesLoad and save .properties configuration files with Properties and NIO.2 readers and writers, use defaults, and keep the file in UTF-8.easy3 min
- File Permissions and FileDescriptorRead and change file permissions with NIO.2 PosixFilePermissions, learn what FilePermission and FileDescriptor are, and where you still meet them.medium4 min
- NIO Buffers and ChannelsChannels move data in blocks between files and ByteBuffers. Learn position, limit and flip, FileChannel reads and writes, and fast transferTo copies.hard5 min
- Memory-Mapped Files in JavaMemory-mapped files let a program read and write a file as if it were memory, using FileChannel.map and MappedByteBuffer. Learn how and when to use them.hard4 min
- WatchService in JavaWatchService notifies a program when files in a folder are created, changed or deleted. Learn how to register a folder, wait for events and process them.medium3 min
28Serialization
- Serialization and Deserialization in JavaSerialization turns a Java object into bytes and deserialization rebuilds it. Learn how it works, what gets saved, object graphs, and when to use it.easy4 min
- Serializable Interface and serialVersionUIDSerializable marks a class as serializable, and serialVersionUID identifies its version. Learn why to declare it, with an InvalidClassException demo.medium5 min
- Transient Keyword in JavaThe transient keyword tells serialization to skip a field. Learn when to use it for passwords, caches and non-serializable objects, and how to restore it.easy4 min
- Serialization with Inheritance and Object ReferencesHow serialization treats superclasses that aren't Serializable, shared references, and cycles, so each object is written once and restored correctly.medium4 min
- Externalizable Interface in JavaExternalizable gives a class full control over its serialized form through writeExternal and readExternal. Learn how it differs from Serializable.medium4 min
- Serializing Records in JavaRecords serialize differently: only their components are saved, and deserialization always goes through the canonical constructor, so validation runs again.medium3 min
- Serialization Security Risks and AlternativesWhy deserializing untrusted data is dangerous, how ObjectInputFilter limits the risk, and why modern Java code prefers JSON and other formats.medium4 min
29Multithreading
- Multithreading in JavaMultithreading lets one Java program do several things at the same time. Learn what a thread is, how it differs from a process, and why threads are useful.easy5 min
- Multitasking: Multiprocessing vs MultithreadingMultitasking means doing several jobs at once. Learn process-based and thread-based multitasking, concurrency vs parallelism, and how Java uses both.easy3 min
- Thread Life Cycle in JavaA Java thread moves through the states NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED. Learn each state and what moves a thread between them.medium4 min
- How to Create a Thread in JavaCreate threads by extending Thread, implementing Runnable or using a lambda, then start them with start(). Learn each way, plus Thread.ofPlatform.easy4 min
- Thread vs Runnable in JavaThread is a class that runs code; Runnable is a task to run. Learn the differences, why Runnable is preferred, and how both relate to lambdas and executors.easy4 min
- Thread Scheduler in JavaThe thread scheduler decides which thread uses a CPU core and for how long. Learn time slicing, preemption, and why thread order is unpredictable.easy4 min
- Thread.sleep() in JavaThread.sleep pauses the current thread for a given time without releasing locks. Learn its forms, the InterruptedException it throws, and its accuracy.easy3 min
- Can We Start a Thread Twice?No: calling start() a second time on the same Thread throws IllegalThreadStateException. Learn why, and how to run the same task again correctly.easy3 min
- Calling Thread.run() Directly vs Thread.start()start() creates a new thread that calls run(); calling run() directly just runs the code in the current thread. See the difference in thread names and timing.easy3 min
- Joining Threads in Javajoin() makes one thread wait for another to finish. Learn join(), join with a timeout, how it shows results safely, and how to wait for many threads.easy4 min
- Naming Threads and the Current ThreadGive threads meaningful names with setName or the constructor, read them with getName, and get the running thread with Thread.currentThread() and threadId().easy3 min
- Thread Priority in JavaThread priorities from 1 to 10 hint to the scheduler which threads matter more. Learn MIN, NORM and MAX_PRIORITY, setPriority, and their limits.easy3 min
- Daemon Threads in JavaDaemon threads are background helpers that don't keep the JVM alive. Learn setDaemon, isDaemon, when the JVM exits, and the risks of daemon threads.easy4 min
- Thread.yield() Method in JavaThread.yield() hints that the current thread is willing to give up the CPU. Learn what it does, why it is only a hint, and what to use instead.easy3 min
- ThreadGroup in JavaThreadGroup is a legacy way to organize threads into groups. Learn what it does, its few remaining uses, and why executors replaced it.easy3 min
- Shutdown Hook in JavaA shutdown hook is a thread the JVM runs when the program is closing. Learn how to add one with Runtime.addShutdownHook, when it runs, and its limits.easy3 min
- Performing Multiple Tasks with Multiple ThreadsRun different tasks in different threads, collect their results safely with join, and build a checkpoint that runs five simulated downloads in parallel.medium5 min
- Interrupting a Thread in JavaInterruption is Java's polite way to ask a thread to stop. Learn interrupt(), isInterrupted(), InterruptedException and how to write stoppable tasks.medium4 min
- Timer and TimerTask in JavaTimer runs TimerTask jobs once or repeatedly on a background thread. Learn schedule, scheduleAtFixedRate and cancel, and what replaced them.easy3 min
30Synchronization
- Synchronization in JavaSynchronization controls how threads access shared data so only one changes it at a time. Learn why it is needed, how monitors work, and the tools Java offers.medium5 min
- Race Conditions and Thread SafetyA race condition happens when the result depends on thread timing. Learn the read-modify-write and check-then-act races, and the ways to make code thread-safe.medium4 min
- Synchronized Methods in JavaA synchronized method locks its object (or class, if static) for the whole method. Learn the syntax, how it protects an object's state, and its costs.easy3 min
- Synchronized Block in JavaA synchronized block locks only the lines that touch shared data, on a lock object you choose. Learn the syntax and why private lock objects are safer.easy4 min
- Static Synchronization in JavaStatic synchronized methods lock the Class object, protecting static fields shared by all instances. Learn the syntax, when it is needed, and a common mistake.easy3 min
- Object Lock vs Class Lock in JavaAn object lock belongs to one instance and guards its data; a class lock belongs to the Class object and guards static data. Compare them with an example.medium4 min
- Deadlock in JavaA deadlock is when threads wait forever for locks held by each other. Learn its four conditions, how to spot one with jstack, and how lock ordering prevents it.hard6 min
- Livelock and Starvation in JavaLivelock is threads busily reacting to each other without progress; starvation is a thread that never gets a turn. Learn both, with examples and fixes.medium5 min
- Inter-Thread Communication in Javawait(), notify() and notifyAll() let threads signal each other through an object's monitor. Learn the rules, the while-loop pattern, and a ready-signal example.hard5 min
- Difference Between Thread.sleep() and Object.wait()sleep() pauses a thread for a time and keeps its locks; wait() releases the lock and waits for a signal. Learn every difference with an example.medium4 min
- Producer-Consumer Problem in JavaProducers add items to a bounded buffer and consumers remove them. Solve the producer-consumer problem with wait/notifyAll, then with BlockingQueue.hard5 min
- Reentrant Monitor in JavaJava's intrinsic locks are reentrant: a thread that holds a lock can enter other code synchronized on the same lock. Learn why this matters, with examples.medium3 min
- Volatile Keyword in JavaThe volatile keyword makes a variable's changes visible to all threads at once. Learn the visibility problem, what volatile guarantees, and what it does not.hard5 min
- Java Memory Model and Happens-BeforeThe Java Memory Model defines when one thread's writes become visible to another. Learn reordering, the happens-before rules, and how to apply them correctly.hard5 min
- Thread-Safe Singleton in JavaMake a singleton safe for many threads: synchronized getInstance, double-checked locking with volatile, the holder idiom and the enum singleton, compared.hard5 min
31Concurrency Utilities
- Executor Framework in JavaThe Executor framework runs tasks on reusable thread pools instead of creating threads by hand. Learn Executor, ExecutorService, Executors and submitting tasks.medium5 min
- Types of Thread Pools in JavaThe Executors class creates fixed, cached, single-thread, scheduled, work-stealing and virtual-thread executors. Learn how each behaves and when to choose it.medium4 min
- ScheduledExecutorService in JavaScheduledExecutorService runs tasks after a delay or repeatedly. Learn schedule, scheduleAtFixedRate and scheduleWithFixedDelay, and how it improves on Timer.medium4 min
- Callable and Future in JavaCallable is a task that returns a result or throws; Future holds that result until it is ready. Learn submit, get, timeouts, cancel and ExecutionException.medium4 min
- Difference Between Runnable and CallableRunnable runs a task with no result; Callable returns a result and can throw checked exceptions. Learn every difference and when to use each.easy3 min
- Shutting Down Executors CorrectlyExecutors must be shut down so their threads end. Learn shutdown, shutdownNow, awaitTermination, close and the recommended two-phase shutdown pattern.medium3 min
- CompletableFuture in JavaCompletableFuture chains async steps with thenApply, thenCompose, thenCombine, allOf, exceptionally and timeouts, ending in a parallel order processor.hard6 min
- Locks in JavaThe Lock interface offers more control than synchronized: ReentrantLock with tryLock and fairness, ReadWriteLock for readers, and StampedLock.hard6 min
- Condition Interface in JavaCondition is the Lock version of wait and notify: await, signal and signalAll, with several separate wait sets per lock. Learn it through a bounded buffer.hard4 min
- Atomic Variables in JavaAtomic classes such as AtomicInteger, AtomicReference and LongAdder update values safely without locks. Learn their methods and when LongAdder wins.medium4 min
- Compare-And-Swap (CAS) in JavaCompare-and-swap updates a value only if it still holds what you expect, retrying otherwise. Learn how atomic classes use CAS loops, and the ABA problem.hard5 min
- VarHandle and Memory OrderingVarHandle gives atomic and ordered access to fields and array elements, with plain, opaque, acquire/release and volatile modes, and when they matter.hard4 min
- False Sharing and @ContendedFalse sharing slows threads that update different variables on the same CPU cache line. Learn about cache lines, measuring the effect, and padding.hard4 min
- Concurrent Collections in JavaConcurrentHashMap, CopyOnWriteArrayList and the BlockingQueue family let many threads share data safely. Learn how they work inside and how to use them.hard6 min
- Synchronizers in JavaSynchronizers coordinate threads: CountDownLatch waits for events, CyclicBarrier and Phaser meet, Semaphore limits access, and Exchanger swaps data.hard5 min
- Fork/Join Framework in JavaFork/Join splits big tasks into smaller ones, runs them in parallel and joins the results with work stealing. Learn RecursiveTask and parallel streams.hard5 min
- ThreadLocal in JavaThreadLocal gives each thread its own copy of a variable. Learn get, set, withInitial and remove, request context, and the leak risk in thread pools.medium4 min
32Modern Concurrency
- Virtual Threads in JavaVirtual threads (Java 21) are lightweight threads managed by the JVM, so a program can run millions of them. Learn how to create them and how they work.medium5 min
- Platform Threads vs Virtual ThreadsCompare platform and virtual threads: cost, scheduling, memory and best uses, then handle 10,000 simulated requests with each and measure the difference.medium5 min
- Virtual Thread Best PracticesUse virtual threads well: never pool them, limit scarce resources with a Semaphore, avoid pinning, watch ThreadLocal, and keep CPU work on platform threads.hard5 min
- Scoped Values in JavaScoped values (final in Java 25) share immutable data with called code for a bounded scope. Learn ScopedValue.where, run, get and nesting, vs ThreadLocal.medium4 min
- Structured Concurrency in JavaStructured concurrency (preview in Java 25) treats related subtasks as one unit with StructuredTaskScope: fork, join, and automatic cancellation when one fails.hard5 min
33JVM Internals and Performance
- Stack vs Heap Memory in JavaThe stack holds method calls and local variables per thread; the heap holds all objects, shared by threads. Learn what goes where and their errors.easy5 min
- JVM Memory AreasThe JVM divides memory into the heap, thread stacks, metaspace, the code cache and other native areas. Learn each area, what fills it, and how to see it.medium5 min
- Where the String Pool LivesSince Java 7, pooled strings live on the heap and the JVM keeps a table of references to them. Learn how to see the pool and how it is garbage collected.medium4 min
- Object Memory Layout in JavaA Java object is a header plus its fields, padded to a multiple of 8 bytes. Learn the header, compressed references, and how to measure object sizes.hard5 min
- Compact Object Headers in Java 25Java 25 can shrink object headers from 12 to 8 bytes with -XX:+UseCompactObjectHeaders. Learn how it works, measure the savings, and when to turn it on.hard4 min
- Object Lifecycle and ReachabilityAn object is created, used while reachable, becomes unreachable, and is then collected. Learn the stages and how objects become unreachable.medium4 min
- Garbage Collection in JavaGarbage collection automatically frees memory of objects the program can no longer reach. Learn what it does, why Java uses it, its costs, and how to watch it.easy4 min
- How Garbage Collection WorksLearn how the JVM finds live objects from GC roots, marks and sweeps or copies them, and why heaps are split into young and old generations.hard5 min
- Garbage Collectors in JavaCompare the JVM's garbage collectors: Serial, Parallel, G1, ZGC and Shenandoah. Learn how each works, their pauses and throughput, and how to choose one.hard4 min
- Safepoints and Stop-The-World PausesA safepoint is a moment when all Java threads stop so the JVM can do work such as GC. Learn why pauses happen, how to log them, and what makes them long.hard4 min
- Reading GC Logs in JavaTurn on GC logging with -Xlog:gc and read each line: the GC type, cause, heap before and after, and pause time. Learn the detailed gc* log and what to look for.medium5 min
- Runtime Class in JavaThe Runtime class reports processors and memory and controls the JVM: availableProcessors, totalMemory, freeMemory, maxMemory, gc, exec and shutdown hooks.easy4 min
- Memory Leaks in JavaA Java memory leak is an object the program no longer needs but still references. Learn the causes, then find and fix a real leak with histograms and dumps.hard6 min
- Strong, Weak, Soft and Phantom ReferencesJava has four reference strengths. Learn how strong, soft, weak and phantom references affect garbage collection, with examples, ReferenceQueue and Cleaner.hard5 min
- Class Loaders in JavaClass loaders find and load classes on demand. Learn the bootstrap, platform and application loaders, the parent delegation model, and when classes are loaded.hard5 min
- Tiered Compilation in JavaThe JVM interprets code first, compiles hot methods quickly with C1, then optimizes the hottest with C2. Learn the tiers, read a real log, and compare speeds.hard5 min
- JIT Optimizations in JavaC2 speeds up hot code with inlining, escape analysis, loop unrolling and speculation, and deoptimizes when assumptions break. See two of them measured.hard5 min
- Common JVM OptionsThe JVM options you will actually use: heap and stack sizes, garbage collector choice, GC logging, heap dumps, containers, and checking a running JVM.medium4 min
- OutOfMemoryError Types and CausesEach OutOfMemoryError message names the memory area that ran out. Learn the heap, Metaspace, direct buffer and thread variants and how to fix each.medium5 min
- JVM Monitoring and Troubleshooting ToolsThe JDK's built-in tools for watching and diagnosing JVMs: jps, jcmd, jstat, jmap, jstack, jinfo, JConsole, VisualVM and Java Flight Recorder, with real output.medium6 min
- Heap Dumps and Thread DumpsA heap dump captures every object; a thread dump shows what every thread is doing. Learn to take and read both to find leaks, hangs and deadlocks.medium7 min
- Benchmarking with JMHTiming Java code with System.nanoTime misleads. Write reliable microbenchmarks with JMH: warmup, forks, @State, @Param, Blackhole and reading results.hard8 min
34Pattern Matching
- Pattern Variable Scope (Flow Scoping)Where can you use a pattern variable? Learn flow scoping: how the compiler decides, with if, else, &&, ||, the ternary operator, early returns and loops.medium7 min
- Pattern Matching for Switch in JavaSwitch on an object's type with case patterns instead of instanceof chains: type patterns, case order and dominance, exhaustiveness, and how it compiles.medium9 min
- Guards in Switch (When Clause)Add a condition to a case pattern with when: guarded patterns, their order, how they affect dominance and exhaustiveness, and the rules for guard expressions.medium6 min
- Handling Null in SwitchWhy switch throws NullPointerException for null, how case null and case null, default fix it, and how null behaves in instanceof and record patterns.medium6 min
- Exhaustive Switch with Sealed TypesCover every subtype of a sealed interface without default, so the compiler flags each switch to update when a type is added. Includes an expression evaluator.medium8 min
- Record Patterns in JavaTake a record apart in one step with a record pattern: nested patterns, var, generics, record patterns in switch, exhaustiveness and the rules.medium8 min
- Unnamed Variables and PatternsUse _ for variables and pattern parts you don't need: in loops, catch blocks, lambdas, try-with-resources, record patterns and multi-pattern cases.easy6 min
- Primitive Types in Patterns (Preview)A Java 25 preview: primitive type patterns in switch and instanceof, switching on long, double and boolean, and safe exactness checks for conversions.hard6 min
35Annotations, Reflection and Bytecode
- Annotations in JavaWhat annotations are and how the built-in ones work: @Override, @Deprecated, @SuppressWarnings, @FunctionalInterface and @SafeVarargs, with compiler output.easy7 min
- Meta-Annotations in JavaAnnotations that describe other annotations: @Retention, @Target, @Documented, @Inherited and @Repeatable, each shown with a runnable example.medium7 min
- Custom Annotations in JavaDeclare your own annotations with @interface: elements, defaults, allowed types and the value shortcut, then read them with reflection in a field validator.medium6 min
- Reflection API in JavaReflection lets a program examine and use classes at run time. Learn the Class object, three ways to get it, what it can tell you, and what reflection costs.medium6 min
- Inspecting Classes, Fields, Methods and ConstructorsUse reflection to list a class's members: getFields vs getDeclaredFields, Field, Method, Constructor and Parameter objects, modifiers and record components.medium6 min
- Creating Objects and Calling Methods with ReflectionCreate objects with Constructor.newInstance, call methods with Method.invoke, handle InvocationTargetException, and build a mini test runner with @Test.medium8 min
- Calling a Private Method Using ReflectionHow setAccessible(true) lets reflection call private methods and change private fields, what still stays protected, and how modules limit deep reflection.medium7 min
- Method Handles in JavaA method handle is a typed, directly callable reference to a method. Learn Lookup, MethodType, invoke vs invokeExact, bindTo, and how it compares to reflection.hard8 min
- Dynamic Proxies in JavaA dynamic proxy is an object created at run time that implements interfaces and sends every call to one InvocationHandler. Learn how Spring-style wrappers work.hard8 min
- Javap Tool in Javajavap is the JDK's class file disassembler. Learn its options (-p, -c, -v, -s, -l), how to read descriptors and the constant pool, and what it reveals.medium9 min
- Bytecode Basics in JavaHow JVM bytecode works: frames, local variable slots, the operand stack, instruction families, a loop traced step by step, and the five invoke instructions.hard9 min
- Creating a Javap ToolBuild your own small javap: read the class file header by hand, then use the Class-File API to list fields, methods and bytecode instructions.hard7 min
36Networking
- Networking Concepts in JavaThe ideas behind every network program: IP addresses, ports, TCP and UDP, client and server, sockets, DNS, and the java.net classes that use them.easy7 min
- InetAddress Class in JavaInetAddress represents an IP address. Learn its factory methods, host name lookups, address checks, IPv4 and IPv6, and InetSocketAddress.easy5 min
- Socket Programming in JavaBuild TCP clients and servers with Socket and ServerSocket: streams, timeouts, common errors, and an echo server that handles many clients at once.medium8 min
- URL Class in JavaTake a web address apart with URL and URI: protocol, host, port, path, query and fragment, relative links, encoding, and why new URL() is deprecated.easy7 min
- URLConnection Class in JavaURLConnection is the classic way to read a resource from a URL: openConnection, request properties, response headers, timeouts and reading the body.medium5 min
- HttpURLConnection in JavaThe legacy HTTP client: request methods, status codes, sending a POST body, reading error responses, and how it compares with HttpClient.medium6 min
- HttpClient in JavaThe modern HTTP client (Java 11): build requests, send them blocking or async, POST JSON, handle status codes and timeouts, and fetch a page title.medium8 min
- DatagramSocket and DatagramPacket in JavaSend and receive UDP packets with DatagramSocket and DatagramPacket: request and reply, timeouts, lost and cut-off packets, and when to choose UDP.medium7 min