Programming Languages
Modern Java from syntax and OOP to collections, concurrency, Spring Boot, build tools and testing.
A path from first program to production-ready Java: the language and its object model, collections and streams, concurrency including virtual threads, then databases, Spring Boot, build tools, testing and logging. It suits beginners and developers coming from another language. Each subject links the official documentation.
The subjects follow the roadmap.sh Java roadmap.
Java is a statically typed, class-based language compiled to bytecode that runs on the JVM. Start with a current LTS JDK (21 or later), write a main method, compile with javac and run with java, then learn the core syntax before touching frameworks.
Every statement ends with a semicolon, blocks use braces, and code lives inside classes. Since Java 11 you can run a single source file directly with java Hello.java, which is handy for experiments.
javac turns source into .class bytecode; the JVM loads classes lazily, verifies and links them, runs static initialisers, then interprets hot code before the JIT compiles it to native machine code.
Eight primitives (byte, short, int, long, float, double, char, boolean) hold values directly; everything else is a reference type. Each primitive has a wrapper class used by generics, with autoboxing in between.
Local variables live inside their enclosing block and must be assigned before use; fields belong to an object or, when static, to the class. var infers a local variable type but the variable stays statically typed.
Widening conversions such as int to long are implicit; narrowing ones need an explicit cast and can silently lose data. Reference casts are checked at runtime and throw ClassCastException, so prefer pattern matching with instanceof.
String is immutable, so concatenating in a loop creates garbage; use StringBuilder instead. Compare with equals, never ==, and know strip, split, formatted, repeat and text blocks.
Integer division truncates and overflow wraps silently unless you use Math.addExact and friends. Use BigDecimal for money, never double, and java.lang.Math for functions like sqrt, pow and floorMod.
Fixed-length, zero-indexed containers created with new int[10] or an initialiser. Their length cannot change; java.util.Arrays provides sort, fill, copyOf and a readable toString.
if/else, the ternary operator and switch. Modern switch expressions use arrows, return a value, never fall through and can pattern-match on types and records.
for, enhanced for (var x : items), while and do/while, with break and continue (optionally labelled). Removing items while iterating with enhanced for throws ConcurrentModificationException.
Java programs are built from classes that bundle state and behaviour. Understanding how objects are created, what each modifier does and how members are shared is the foundation for every library and framework you will use.
A class is a blueprint; new allocates an object on the heap and runs a constructor. Variables hold references to objects, so two variables can point at the same instance.
Fields store an object's state and methods operate on it. Keep fields private and expose behaviour, not setters for everything.
public, protected, package-private (no keyword) and private control visibility. Default to the narrowest level that works; package-private is underused and great for internals.
Static fields and methods belong to the class, not to instances. Mutable static state is effectively global and makes testing and concurrency harder, so reserve it for constants and pure helpers.
Static nested classes are just namespaced; inner classes hold a hidden reference to the outer instance, which can leak memory. Local and anonymous classes are mostly replaced by lambdas today.
A final variable cannot be reassigned (the object it points to can still change), a final method cannot be overridden and a final class cannot be extended.
The deeper half of Java's object model: inheritance and interfaces, how method calls are resolved, newer constructs like records and enums, and how arguments are passed. These explain most surprising behaviour in real code.
Methods that return this (or a new immutable object) let calls be strung together, as in builders, StringBuilder and streams. Keep chains readable by putting one call per line.
Type-safe sets of constants that are full classes: they can have fields, constructors and methods, and work in switch. EnumMap and EnumSet are fast, compact collections keyed by them.
A record declares an immutable data carrier in one line, generating the constructor, accessors, equals, hashCode and toString. Validate inputs in a compact constructor.
Namespaces that group related types and match the directory layout, named by reversed domain like com.example.billing. They also form the boundary for package-private access.
Instance initialiser blocks run before the constructor body on every construction; static { } blocks run once when the class is initialised. Constructors or factory methods are usually clearer.
Objects are allocated, used while reachable, then reclaimed by the garbage collector at an unpredictable time. Do not rely on finalize (deprecated); release resources with try-with-resources.
extends reuses and specialises a single superclass; every class ultimately extends Object. Deep hierarchies are brittle, so favour composition and use sealed classes to restrict who may extend.
Expose what a type does and hide how. Abstract classes share partial implementation and state; interfaces define capabilities a class can mix in.
Keep fields private and change state only through methods that protect invariants. Return defensive copies or unmodifiable views of internal collections.
Overloading means same name, different parameters, chosen at compile time. Overriding replaces a superclass method at runtime; always mark it @Override so the compiler catches signature typos.
Static, private and final methods and overload selection are bound at compile time from declared types; overridden instance methods are dispatched at runtime by the object's actual class.
Contracts a class implements; a class can implement many. They can hold default, static and private methods, and sealed interfaces plus records model closed sets of variants.
Java is always pass-by-value: for objects the value copied is the reference. A method can mutate the object you passed but cannot make your variable point somewhere else.
The Collections Framework gives you interfaces (List, Set, Map, Queue, Deque) and implementations with different performance trade-offs. Program to the interface, pick the implementation for the access pattern, and use List.of/Map.of for immutable values.
Arrays are fixed-size and can hold primitives; ArrayList grows automatically but boxes primitives. Use ArrayList by default and arrays for performance-critical primitive data.
A collection without duplicates: HashSet for speed, LinkedHashSet to keep insertion order, TreeSet for sorted order. Elements need consistent equals and hashCode.
Key-value lookup: HashMap, LinkedHashMap (which can act as an LRU cache) and TreeMap. computeIfAbsent, merge and getOrDefault remove most manual null checks.
Holds elements for processing, usually first-in-first-out. Prefer offer/poll/peek, which return a value instead of throwing; PriorityQueue orders by a comparator.
Last-in-first-out access. The legacy Stack class is synchronized and extends Vector; use ArrayDeque with push and pop instead.
A Deque (double-ended queue) adds and removes at both ends, so it serves as both a queue and a stack. ArrayDeque is the usual implementation and rejects nulls.
The protocol behind enhanced for loops: hasNext, next and optionally remove. Calling Iterator.remove is the safe way to delete while iterating; removeIf is shorter still.
Type parameters like List<String> give compile-time safety and remove casts. Generics are erased at runtime, and wildcards (? extends, ? super) make APIs flexible: producer extends, consumer super.
Checked exceptions must be declared or caught; unchecked ones (RuntimeException subclasses) need not be. Catch only what you can handle, keep the original exception as the cause when wrapping, and use try-with-resources so AutoCloseable resources always close.
Lambdas such as x -> x * 2 are compact implementations of a functional interface, and method references like String::length are shorter still. They can only capture effectively final local variables.
Since Java 8 the language supports a functional style: passing behaviour as values, composing small functions and processing data as pipelines rather than loops. It pairs well with immutable records.
Building new functions from existing ones: Function.andThen and compose, Predicate.and/or/negate, and Comparator.comparing(...).thenComparing(...).
Methods that take or return functions, such as map, filter, Comparator.comparing or a factory returning a configured Predicate. They let you separate the what from the how.
Interfaces with exactly one abstract method, the target type of lambdas. Know Function, Supplier, Consumer, Predicate, BiFunction and the primitive variants; annotate your own with @FunctionalInterface.
Lazy pipelines of filter, map and flatMap ending in a terminal operation like collect, toList or reduce. Streams are single-use; avoid side effects inside them and measure before using parallel().
Metadata attached to code, such as @Override, @Deprecated and @SuppressWarnings. Frameworks read them at runtime through reflection or at compile time through annotation processors (Lombok, MapStruct); retention and target decide where they apply.
The Java Platform Module System (Java 9) adds module-info.java, where a module declares what it requires and which packages it exports. It gives strong encapsulation and lets jlink build trimmed runtimes, though many applications still run on the classpath.
Optional<T> makes "maybe no value" explicit in return types. Chain map, filter and orElse/orElseThrow instead of calling get; do not use it for fields or parameters, and never return null from a method declared to return Optional.
Objects receive their collaborators from outside instead of constructing them, which makes code testable and configurable. Prefer constructor injection; containers like Spring, Jakarta CDI or Dagger wire the object graph for you.
Use java.time, not Date or Calendar: Instant for machine timestamps, LocalDate/LocalDateTime for wall-clock values, ZonedDateTime when a zone matters, and Duration/Period for amounts. All types are immutable and thread-safe.
Low-level Socket/ServerSocket and URI live in java.net; for HTTP use the built-in java.net.http.HttpClient (Java 11+), which supports HTTP/2, async calls and timeouts. Always set connect and request timeouts.
Compile a pattern once with Pattern.compile and reuse it; Matcher gives find, matches and groups. Backslashes must be doubled in string literals, and String.split and replaceAll take regexes, not plain text.
Byte streams (InputStream/OutputStream) and character streams (Reader/Writer), usually wrapped in buffered versions. Always specify a charset such as UTF-8 and close streams with try-with-resources.
Prefer NIO.2 (java.nio.file) over the old File class: Path for locations and Files for readString, writeString, lines, walk, copy and move. Close the streams returned by Files.lines and Files.walk.
The Java Cryptography Architecture exposes MessageDigest, Cipher, Mac, KeyGenerator, Signature and SecureRandom through pluggable providers. Use AES-GCM for encryption, a dedicated password hash (PBKDF2, bcrypt, Argon2) for passwords, and never invent your own scheme.
Java has threads, locks and a rich java.util.concurrent toolkit: executors, concurrent collections, atomics and CompletableFuture. Most bugs come from shared mutable state, so prefer immutability and high-level utilities over raw synchronized and wait/notify.
Platform threads map one-to-one to OS threads and are expensive. Run tasks through an ExecutorService rather than creating threads by hand, and always shut executors down.
Lightweight threads managed by the JVM (final in Java 21) that let blocking, thread-per-request code scale to millions of tasks. Do not pool them, and watch for pinning on long synchronized blocks in older JDKs.
Defines when a write by one thread is guaranteed visible to another through happens-before edges, created by locks, volatile, thread start/join and final fields. Without them, threads may see stale or reordered values.
A volatile field guarantees that reads see the latest write and prevents reordering around it, but it does not make compound actions like count++ atomic; use AtomicInteger or a lock for those.
Everything sits on JDBC; ORMs and repositories add mapping and convenience on top. Use a connection pool (HikariCP), parameterised queries, and keep an eye on the SQL your ORM actually generates.
The standard low-level API: get a Connection from a DataSource, run PreparedStatements, read ResultSets and manage transactions. Always use bind parameters to prevent SQL injection.
The most widely used JPA implementation, mapping entities to tables with dirty checking and lazy loading. Watch for N+1 queries and LazyInitializationException; fetch joins and entity graphs fix most of them.
Generates repository implementations from interfaces, deriving queries from method names like findByEmail and supporting @Query, paging and specifications on top of JPA.
A lighter ORM without a session/entity-manager to manage, with type-safe query beans generated at build time. Worth a look if JPA feels heavy.
Most Java web work happens in a framework that handles HTTP, dependency injection, configuration and data access. Spring Boot dominates jobs; Quarkus and others trade ecosystem size for faster startup or simplicity.
Spring provides the DI container and modules for web, data and security; Boot adds auto-configuration, starters and an embedded server so java -jar app.jar just works. Learn profiles, @ConfigurationProperties and Actuator.
A Kubernetes-oriented framework that does much of its work at build time, giving fast startup and low memory, plus GraalVM native images. Uses Jakarta EE and MicroProfile APIs and has a live-reload dev mode.
A small, unopinionated web library for Java and Kotlin: register handlers like app.get("/users", ctx -> ...) with no annotations or container magic.
A stateless, reactive framework for Java and Scala built on Pekko, with hot reload and an asynchronous request model.
Build tools resolve dependencies from Maven Central, compile, run tests and package jars. Learn one well, commit its wrapper script (mvnw or gradlew) so everyone builds with the same version.
Declarative XML builds in pom.xml with a fixed lifecycle (compile, test, package, install) and convention-based layout. Predictable and still the most common choice in enterprise projects.
Builds scripted in Kotlin or Groovy DSL with incremental compilation and a build cache, making it fast on large projects. It is the standard for Android and popular with Spring.
Google's build system for large multi-language monorepos, with hermetic, reproducible builds and remote caching. Overkill for a single service.
Fast unit tests for logic, integration tests against real dependencies (often started with Testcontainers), and behaviour tests that read like specifications. Run them on every build so regressions are caught before merge.
The standard unit testing framework: @Test, lifecycle hooks like @BeforeEach, parameterised tests, and assertions such as assertThrows. Most tools and IDEs integrate with it out of the box.
An alternative test framework with flexible groups, dependencies between tests and data providers, still common in Selenium-based suites.
Mockito creates test doubles with mock, stubs them with when(...).thenReturn(...) and checks interactions with verify. Mock only what you own and what is slow or external.
A fluent DSL for testing HTTP APIs: given().when().get("/users").then().statusCode(200) with JSON path assertions on the body.
Apache's load testing tool: build test plans with thread groups, samplers and assertions, then run them headless with jmeter -n in CI.
Runs Gherkin scenarios (Given/When/Then) written in plain language against Java step definitions, for behaviour-driven development with non-developers.
Code against a facade (SLF4J) and choose a backend at deploy time. Use parameterised messages, log at the right level, prefer structured JSON logs in production and never log secrets or personal data.
The de facto logging facade: LoggerFactory.getLogger(...) and log.info("user {} logged in", id). Exactly one binding should be on the classpath.
The native SLF4J backend and Spring Boot's default, configured with logback.xml appenders, encoders and rolling policies.
Apache's backend, known for async loggers with high throughput. Stay on a patched version: the 2021 Log4Shell vulnerability affected older 2.x releases.
A tiny, fast logging library with a static Logger API and minimal configuration, useful for small apps and tools.
Document public APIs where they are declared, explaining contracts, units and edge cases rather than restating the code. Generated reference docs are published alongside every library release.
/** ... */ comments with tags like @param, @return and @throws, turned into HTML by the javadoc tool. Java 18 added @snippet for compiled, checkable code examples.