Java Tutorials
Java from your first program to the features you will actually use at work — variables and types, control flow, classes and interfaces, collections and exceptions, then lambdas, streams, Optional, records and sealed classes. Written against Java 21, kept short on purpose, and every code sample compiles.
- Java Code SnippetsThe last post in the track is a reference rather than a lesson: the lookups you will make over and over, in one place. Every snippet here compiles as written against Java 21. Strings Numbers and parsing Dates and times Collections Iterating Streams Files Records, Optional and switch Async with…
- Java Best PracticesThese are the habits that separate code a team can maintain from code they quietly rewrite. None of them is clever. All of them compound. Name things properly You write a name once and read it for years. The conventions are fixed and universal: PascalCase for types, camelCase for methods and…
- How to Solve Java ProblemsEveryone gets stuck. The difference between an hour and a day is having a method instead of guessing. This post is that method — four steps, in order — plus the errors every Java beginner hits and what each one is really telling you. 1. Read the error. Actually read it. The most common mistake is…
- DebuggingDebugging is a skill, not a talent, and most of it is one habit: read the error before you do anything else. Java's errors are unusually informative, and beginners routinely skip past them to start guessing. Reading a stack trace Four pieces of information, in order of usefulness: The message.…
- Eclipse Hot KeysLearning your IDE's shortcuts is one of the highest-return investments a developer makes, because the saving is small and repeated thousands of times. This is the Eclipse set worth memorising, with the IntelliJ equivalent alongside — most teams have both. Windows and Linux bindings are given first;…
- Encryption and DecryptionJava's cryptography lives in javax.crypto and java.security . The single most important thing to know about it is that you should use it as little as possible: reach for a proven library or a managed service, and treat the raw API as something you need to read rather than write. This post covers…
- log4jLogging is what you have instead of a debugger when the problem happened at 3am on a server you cannot attach to. Java's logging landscape has a confusing number of libraries; the arrangement that matters is simple once you see it. The facade and the implementation There are two layers, and…
- DatabaseJDBC is the API every Java database access sits on — Hibernate, Spring Data, jOOQ and every ORM eventually call it. You will rarely write it directly, and knowing what it does is what lets you diagnose the layers above it. The shape Four objects: a Connection to the database, a PreparedStatement…
- RegexA regular expression describes a pattern of text. Java's support lives in java.util.regex , and the hardest part is not the syntax — it is knowing when a regex is the right tool and keeping the ones you write readable. The three ways in Compile the pattern once if it is used more than occasionally.…
- MultithreadingThreads let a program do several things at once. They also introduce a class of bug that is intermittent, unreproducible and dependent on timing — which is why the most useful advice about concurrency is to use the highest-level tool that solves your problem. Starting a thread start() creates a…
- GenericsGenerics let a class or method work with a type supplied by the caller, checked at compile time. List is the everyday face of it. Writing your own is less common, and understanding erasure explains most of the surprising rules. What they buy you Two gains: mistakes move from runtime to compile…
- Java 25 Migration Guide (21→25)Java 21 to 25 is the smallest LTS-to-LTS step Java has had. Nothing significant was removed from the API, the language changes are additive, and most applications move by changing one number. This post covers what to check anyway. The one-line version Upgrade build plugins and dependencies first,…
- Java 25 Other ImprovementsJava 25 is the current LTS. The features with their own posts — compact source files , gatherers and flexible constructors — are the visible ones. This collects what else arrived between 21 and 25. Scoped values A replacement for ThreadLocal , and the reason it exists is virtual threads . A…
- Java 25 Flexible Constructor BodiesUntil Java 25, super() or this() had to be the very first statement in a constructor. Nothing could run before it. Flexible constructor bodies lift that restriction, which means you can finally validate an argument before handing it to the superclass. The restriction That rule existed for a good…
- Java 25 Stream GatherersStreams have had a fixed set of intermediate operations since Java 8 — filter , map , flatMap , distinct , sorted , and a handful more. You could add your own terminal operation with a Collector , but there was no way to add an intermediate one. Gatherers are that missing extension point. The gap…
- Java 25 Module Imports & Simple Source FilesJava 25 finalised two changes aimed squarely at the first hour of learning Java: a program no longer needs a class declaration or a static main , and a single import can pull in a whole module. Together they make a first Java file three lines long. The first program, then and now That version asks…
- Java 21 Migration Guide (17→21)Java 17 to 21 is the easiest LTS upgrade in years. Nothing significant was removed, the language changes are additive, and most applications move with a version bump and a test run. This post covers the few things that do bite. If you are coming from Java 8 or 11 rather than 17, read the Java 17…
- Java 21 Other ImprovementsVirtual threads dominated the Java 21 release notes, and several smaller additions arrived alongside them. These are the ones worth knowing about. String templates — and why you cannot use them Worth addressing first because you will find articles recommending them. String templates were previewed…
- Java 21 Unnamed Variables and PatternsAn unnamed variable is written _ and says "something goes here and I will not use it". It removes the invented names — ignored , unused , e2 — that clutter code where a value is structurally required but genuinely irrelevant. A note on versions This was a preview feature in Java 21, not a standard…
- Java 21 Sequenced CollectionsJava 21 added three interfaces — SequencedCollection , SequencedSet and SequencedMap — giving every collection with a defined order the same way to ask for its first and last element, and to iterate backwards. It is a small addition that fixes a twenty-five-year-old inconsistency. The inconsistency…
- Java 21 Record PatternsA record pattern matches a record and pulls its components out in the same step. It is a small piece of syntax that removes the accessor calls from every branch of a type switch , and it composes to arbitrary depth. It only works on records , and that is not an arbitrary restriction. A record…
- Java 21 Pattern Matching for switchJava 21 lets a switch match on types, not just constants. Combined with sealed types , it turns a chain of instanceof checks into something the compiler can prove is complete. The chain it replaces Each case tests a type and binds a variable of that type, the same as instanceof pattern matching .…
- Java 21 Virtual ThreadsA virtual thread is a thread that costs almost nothing to create. You can have millions of them. That single change removes the reason most server code was written asynchronously, and it is the biggest thing to happen to Java concurrency in twenty years. The problem A platform thread — the only…
- Java 17 Migration Guide (11→17)Moving from Java 11 to 17 is a much smaller job than 8 to 11. Nothing large was removed from the JDK. The one change that breaks builds is strong encapsulation — reflective access into JDK internals stopped being a warning and became an error. The change that matters Java 9 hid the JDK's internal…
- Java 17 Other ImprovementsSix years and three LTS releases separate Java 11 from Java 17. The headline features get their own posts; this one collects the smaller changes that arrived in between and are easy to miss entirely — several of which you have probably already benefited from without noticing. Helpful…
- Java 17 Pattern Matching for instanceofEvery instanceof check used to be followed by a cast to the type you had just checked for. Pattern matching folds the two into one, and the compiler tracks where the result is valid. It is a small change that removes a line from a very common shape. The old shape s is a pattern variable . It exists…
- Java 17 Text BlocksA text block is a string literal delimited by three quotes that can span lines without escaping. It exists because embedded JSON, SQL and HTML were genuinely painful to read in Java, and the workarounds — concatenation, \n everywhere, external files — were all worse than the problem. The problem…
- Java 17 Switch ExpressionsThe switch statement Java inherited from C had two design flaws: it fell through unless you wrote break , and it could not produce a value. Java 14 fixed both, and Java 17 made it standard. The old form still works; there is no reason to write it in new code. Arrow labels With -> only the matching…
- Java 17 Sealed ClassesA sealed type declares exactly which types may extend it. The compiler enforces the list, and — this is the real payoff — it can then prove that a switch over that type has covered every case. The problem An ordinary interface is open: anyone, anywhere, can implement it. That is usually the point.…
- Java 17 RecordsA record is a class whose job is to carry data. You declare the components; the compiler writes the constructor, the accessors, equals , hashCode and toString . One line replaces about sixty. The sixty lines it replaces Every one of those hand-written members is a place a bug can hide — an equals…
- Java 11 Removed/Deprecated Features & MigrationJava 11 is the upgrade that breaks things. Not because the language changed — it barely did — but because Java 11 removed several modules that had been part of the JDK since the 1990s. Most upgrades from 8 fail for the same handful of reasons, and they are all fixable. Why this one hurts Java 9…
- Java 11 Running Java Files DirectlySince Java 11 you can run a .java file directly, with no separate compile step and no .class file left behind. It sounds like a convenience for beginners, and it is, but it also makes Java usable for the kind of quick script you would otherwise have written in Python. The change Note the difference…
- Java 11 HttpClient APIJava 11 shipped a real HTTP client in the JDK. Before it, making an HTTP call meant either HttpURLConnection — an API from 1997 that nobody enjoyed — or adding Apache HttpClient or OkHttp as a dependency. Now a simple GET is four lines with nothing on the classpath. Three objects The whole API is a…
- Java 11 New File and Collection MethodsBeyond the String methods , Java 11 added a handful of small API improvements. Each one removes a few lines you used to write by hand, and two of them — Files.readString and Path.of — you will use constantly. Reading and writing a whole file Both default to UTF-8, which is the important detail. The…
- Java 11 New String MethodsJava 11 added five small String methods. None of them is clever, and together they delete a surprising amount of the utility code every project used to carry — the null-and-whitespace check, the manual line splitter, the loop that repeats a character. isBlank() isBlank() is what people usually mean…
- CompletableFutureCompletableFuture runs work on another thread and lets you describe what should happen when it finishes — without blocking to wait for it. It is how you stop making a caller wait for three slow things in sequence when they could happen at once. Starting work supplyAsync when you want a value back,…
- Array Parallel SortArrays.parallelSort sorts an array using every core on the machine instead of one. It is a single-word change from Arrays.sort , which makes it tempting to use everywhere — and it is slower than the sequential version on most of the arrays you will actually sort. Using it Like Arrays.sort , it…
- StringJoinerBuilding a comma-separated string is one of those jobs that looks trivial and produces a trailing comma every time. StringJoiner is the small class Java 8 added to stop that happening, and two shorter forms cover most of what you would use it for. The problem Everyone writes this once, and everyone…
- Date Time APIJava has two date APIs. The old one — Date , Calendar , SimpleDateFormat — is mutable, not thread-safe, and confusing enough that it was replaced. The modern one, java.time , arrived in Java 8 and is what you should use for everything. This matters more than most "prefer the new API" advice,…
- Interface default methods and static methodsBefore Java 8, adding a method to an interface broke every class that implemented it. That is not a theoretical problem — it is why Collection went years without obvious conveniences. Default methods solved it, and understanding why they exist tells you when to use them. The problem they were…
- ForeachforEach runs a piece of code once per element. It arrived with Java 8 as the functional counterpart to the for-each loop, and choosing between the two is mostly a readability question rather than a technical one. The method It takes a Consumer — one argument in, nothing out. That shape is the whole…
- OptionalOptional is a container that either holds a value or is empty. Its purpose is not to eliminate null — it is to move "there might be nothing here" out of your head and into the type signature, where the compiler and the next reader can both see it. The problem it solves Nothing forces a caller of…
- Collectors classA stream pipeline has to end somewhere. collect is the general-purpose ending, and the Collectors class supplies the recipes — turn this stream into a list, a map, a grouped report, or one joined string. There are dozens of them and you do not need dozens. Six do almost all the work in practice,…
- StreamsA stream lets you describe what you want done to a collection instead of writing the loop that does it. It is the single biggest change in how Java is written since Java 8, and the mental model is small: a source, some intermediate operations, and one terminal operation that makes it all run. The…
- Method ReferencesA method reference is a lambda with the noise removed. When a lambda does nothing but call one existing method, :: lets you name that method instead of describing the call. They compile to the same thing — the method reference is not faster, and it is not a different mechanism. It is the same…
- Functional InterfacesA functional interface is an interface with exactly one abstract method. That single rule is what makes lambdas work: when the compiler sees a lambda, it needs to know which method the lambda is implementing, and one abstract method means there is no ambiguity. The rule, and the annotation…
- Lambda ExpressionA lambda is a function you can pass to a method as if it were a value. That is the whole idea, and it works because of one rule: a lambda is shorthand for implementing an interface that has exactly one abstract method. Understand that rule and lambdas stop looking like magic. Where they came from…
- Exception HandlingAn exception is Java's way of saying "I cannot continue, and here is exactly why". Handling them well is mostly about restraint: catching only what you can actually do something about, and never hiding what you cannot. try , catch , finally The try block holds code that might fail. The catch runs…
- CollectionsCollections are the containers you reach for in every program: a list of orders, a set of tags, a map from id to customer. Java gives you four shapes and several implementations of each. Picking one should take about five seconds, and this post is mostly about making that true. The four shapes…
- PackagesA package is a namespace. It groups related classes, prevents name collisions between unrelated libraries, and — through access modifiers — decides who can see what. Two classes called Order can coexist happily as long as they live in different packages. Declaring a package The package line must be…
- Static and Final KeywordsTwo small keywords that get confused with each other constantly. They are unrelated: static means "belongs to the class, not to an object" , and final means "cannot be reassigned" . Neither implies the other. static fields: one copy, shared Access a static field through the class name —…
- Java InterfaceAn interface is a contract: a list of methods a class promises to provide, with no state and (mostly) no implementation. It is the main tool Java gives you for writing code that does not depend on a specific class — and that is what makes code testable and changeable. Declaring and implementing one…
- Java OOPObject-oriented programming is four ideas. Most explanations define them; this post shows each one in code and says what it is actually for — because the fourth idea, inheritance, is the one beginners reach for constantly and professionals reach for rarely. 1. Encapsulation — hide the data, expose…
- Java ClassA class is a blueprint. It says what data an object holds and what it can do, and then you create objects from it. Every line of Java you have written so far lived inside one. Fields, constructor, methods Note that the class holds the data and the rules about that data together. The check in…
- Java MethodA method is a named block of code that takes inputs and optionally produces a result. Methods are how you stop repeating yourself and how you break a large problem into pieces small enough to understand one at a time. Anatomy public — who can call it. Packages covers the four options. int — the…
- Java ArraysAn array is a fixed-size, indexed block of values that all share one type. It is the simplest container Java has, it is what ArrayList is built on, and the moment you need it to grow you should stop using it. Creating an array Two things to fix in your head now. The size is permanent — an int[5]…
- Java For LoopA loop runs a block repeatedly. Java has four, but the choice between them is nearly mechanical: if you are walking a collection, use for-each; if you are counting, use a classic for ; if you do not know how many times, use while . This post covers all four and the two mistakes everyone makes at…
- Java Conditional StatementsConditionals are how a program chooses. Java gives you three tools — if , the ternary, and switch — and switch changed substantially in recent versions, in a way that removed the language's most notorious source of accidental bugs. if , else if , else The branches are tested top to bottom and the…
- Java StringString is the type you will use more than any other, and it has one property that explains nearly all of its behaviour: a String is immutable . Once created, its characters can never change. Every method that appears to modify a string actually returns a new one. Immutability, and what it means in…
- Java OperatorsOperators are the symbols that do things to values. Most of them behave exactly as you would guess from school arithmetic. This post covers all of them quickly, then spends its time on the four that do not behave as you would guess — which is where the bugs are. Arithmetic Trap 1: integer division…
- Java Data TypesJava splits every value into one of two worlds: primitives , which are raw values, and reference types , which are objects. There are exactly eight primitives and you need all of them. Everything else — String , arrays, your own classes — is a reference type. Knowing which world a value lives in…
- Java VariablesA variable is a named box that holds a value of a declared type. That definition sounds trivial and it is, but three things about variables in Java are not: the type is fixed, where you declare one decides how long it lives, and Java has three distinct kinds that behave differently. Declaring and…
- Introduction to JavaPeople use the word "Java" for three different things: a language, a compiler, and a virtual machine. Most of the confusion beginners have about Java comes from not noticing that. This post separates them, then explains why the arrangement was worth building and where it leaves Java in 2026. Three…
- Java – Get StartedThis is the first post in a 29-part Java track. It gets you from nothing installed to a program you wrote and ran, tells you which Java version everything here assumes, and then hands you the map of the other 28 posts. You do not need any programming experience. You do need about twenty minutes and…