# Repository Overview

Welcome! If you're new to this codebase, you've landed in the right place. This repository is a collection of Java examples authored by [biezhi](https://github.com/biezhi) that showcase language and platform features introduced in Java 9 through Java 11. Every subpackage is a self-contained demo — no external frameworks, no build orchestration, no production-grade application logic. Think of it as a curated notebook for engineers who want to see how modern Java idioms work in practice, with runnable code and clear comments.

## Overview

This project is an educational showcase organized under the package `io.github.biezhi.java11`. It covers 10 distinct topic areas, each with its own package and a single `Example` class (with occasional supporting classes like `Foo`). The examples are minimal by design: each one runs from a `main()` method, exercises a specific API or language feature, and prints results to the console. Nothing depends on anything else in the repository, and no third-party libraries are required (except Gson in the `http` example, which is used for JSON serialization).

The repository is intended for learning, quick reference, or as inspiration when introducing newer Java features into a codebase. It is not production-ready software.

## Technology Stack

This is a pure Java project targeting **Java 11** (JDK 11). No external frameworks or application servers are used. The only features relied upon are those shipped with the JDK itself:

| Feature | First introduced | Used in package(s) |
|---|---|---|
| `var` (local variable type inference) | Java 10 | `var` |
| Diamond operator with anonymous inner classes | Java 9 | `collections` |
| Private methods in interfaces | Java 9 | `interfaces` |
| Immutable collection factories (`List.of`, `Map.of`, `Set.of`) | Java 9 | `collections` |
| `ProcessHandle` API improvements | Java 9 | `processor` |
| `TimeUnit.convert(Duration)` | Java 9 | `time` |
| Improved try-with-resources (effectively final vars) | Java 9 | `trywithresources` |
| `Files.readString()` / `Files.writeString()` | Java 11 | `files` |
| `HttpClient` API (HTTP/2, async, proxy, auth) | Java 11 | `http` |
| `String.repeat()`, `String.lines()`, `String.strip()`, `String.isBlank()` | Java 11 | `string` |
| JEP 330: Single-file source execution | Java 11 | `singlefile` |

**Optional dependency:** The `http` example uses **Gson** (`com.google.gson.Gson`) for serializing a test POJO to JSON. This is the only third-party library in the codebase, and it is used in a single method (`asyncPost`).

## Architecture

This repository has no layered architecture, no dependency injection, and no external-facing components. Instead, it is organized as a flat set of independent example packages. Below is a diagram of the package structure:

```mermaid
flowchart TD
    subgraph Root["io.github.biezhi.java11 — Java 11 Feature Showcase"]
        collections["collections<br/>Collection factories and diamond operator"]
        files["files<br/>Files.readString/writeString"]
        http["http<br/>HttpClient API"]
        interfaces["interfaces<br/>Private methods in interfaces"]
        processor["processor<br/>ProcessHandle API"]
        singlefile["singlefile<br/>JEP 330 single-file execution"]
        string["string<br/>String.strip/lines/isBlank"]
        time["time<br/>Duration-TimeUnit bridging"]
        trywithresources["trywithresources<br/>Java 9 try-with-resources"]
        var["var<br/>JEP 286 type inference"]
    end
```

Each package is a leaf node — there are no inter-package dependencies, no shared base classes, and no orchestration layer. The only "entry point" is any package's `Example.main()` method, which can be invoked directly.

## Module Guide

### `collections`

**Purpose:** Demonstrates two complementary collection-related features — the diamond operator with anonymous inner classes (improved in Java 9) and the immutable collection factory methods introduced in Java 9.

**Key classes:**
- **`Example`** — Walks through every factory method on `List.of()`, `Map.of()`, `Set.of()`, `Map.ofEntries()`, and `Map.entry()`. Shows that all returned collections are immutable and documents the JDK version each method appeared in.
- **`DiamondOperatorExample`** — Contains a nested `MyHandler<T>` abstract class and exercises the diamond operator (`<>`) with anonymous subclasses in three patterns: explicit type parameter, wildcard (`? extends T`), and unbounded wildcard (`?`).

This is a good starting point if you want to understand modern Java collection idioms or how anonymous inner classes became more ergonomic.

### `files`

**Purpose:** Demonstrates the two new text-file convenience methods added to `java.nio.file.Files` in Java 11: `readString()` and `writeString()`.

**Key classes:**
- **`Example`** — Writes a string to a file, reads it back, compares the round-trip, and cleans up. The entire operation is four lines of code, compared to the verbose stream-based boilerplate that preceded it.

The module highlights how Java 11 simplified one of the most common I/O patterns by providing UTF-8-aware, single-line methods instead of requiring manual stream management.

### `http`

**Purpose:** Showcases the modern `java.net.http.HttpClient` API introduced in Java 11 — a complete replacement for the older `java.net.URL`-based approach.

**Key classes:**
- **`Example`** — Contains a suite of static methods each demonstrating a different capability: synchronous GET, asynchronous GET, asynchronous POST with JSON, file download, file upload, proxy configuration, basic authentication, HTTP/2, and concurrent batch requests.
- **`Foo`** — A minimal POJO with `name` and `url` fields, used as the serialization target for the POST example.

This is the largest and most feature-rich example in the repository. If you're looking for a reference on how to use the JDK 11 HTTP client in various configurations (proxy, auth, HTTP/2, async), this package covers it all.

### `interfaces`

**Purpose:** Demonstrates private methods in interfaces, a feature introduced in Java 9 that solved the code-reuse problem for default methods.

**Key classes:**
- **`Example`** — An interface that contains all four kinds of method declarations: abstract (traditional), default (Java 8), private instance, and private static. The default methods (`interfaceMethodWithDefault()` and `anotherDefaultMethod()`) both delegate to the private helper `init()`, illustrating the intended use case: sharing internal logic between default methods without exposing it as a public API.

Note that this feature was introduced in Java 9, not Java 11, but it lives here because the project groups all "modern Java" demos under a `java11` umbrella.

### `processor`

**Purpose:** Demonstrates the Process API improvements introduced in Java 9, specifically the `ProcessHandle` and `ProcessHandle.Info` APIs for inspecting and managing OS-level processes.

**Key classes:**
- **`Example`** — Gets a handle for the current JVM process and prints its native OS PID. This is intentionally minimal — the real value is in the API reference, which also supports tree traversal (`children()`, `parents()`, `descendants()`), lifecycle management (`isAlive()`, `onExit()`, `destroy()`), and detailed metadata (`info().command()`, `info().startInstant()`, etc.).

### `singlefile`

**Purpose:** Demonstrates JEP 330 — Java 11's ability to compile and run a single source file directly via the `java` launcher, without an explicit `javac` step.

**Key classes:**
- **`HelloWorld`** — A one-method class that prints a greeting. The entire point is that you can run it with a single command: `java HelloWorld.java`.

This is the simplest module in the repository. It's a one-file, one-method example that proves JEP 330 works and shows why it matters for prototyping and scripting.

### `string`

**Purpose:** Demonstrates the new `String` methods added in Java 11: `repeat()`, `lines()`, `strip()`, `stripLeading()`, `stripTrailing()`, and `isBlank()`.

**Key classes:**
- **`Example`** — Contains a `writeHeader()` helper and a public demonstration method for each new String API. Methods print before/after examples so the console output makes the behavior clear. The `main()` method currently calls only `lines()`; other demonstrations are left commented out for interactive exploration.

The module is particularly useful for understanding the difference between the new Unicode-aware `strip()` methods and the legacy `trim()` method, and for learning how `lines()` returns a `Stream<String>` that integrates with the Stream API.

### `time`

**Purpose:** Demonstrates bridging the legacy `java.util.concurrent.TimeUnit` API with the modern `java.time.Duration` API — a conversion capability added in Java 9.

**Key classes:**
- **`Example`** — Converts `Duration` values into `TimeUnit`-based results (e.g., `TimeUnit.DAYS.convert(Duration.ofHours(24))` yields `1`). Shows that truncation happens toward zero, not by rounding.

This module addresses a real-world pain point: many concurrent utilities (`ScheduledExecutorService`, `Lock.tryLock()`, etc.) still require `TimeUnit`-based timeouts, while `java.time.Duration` is the modern way to represent time spans. The module shows that a single method call bridges the gap.

### `trywithresources`

**Purpose:** Demonstrates the Java 9 improvement to try-with-resources that allows effectively-final resource variables to be declared outside the `try` block.

**Key classes:**
- **`Example`** — Declares a `BufferedReader` outside the `try` statement and references it inside — a pattern that was not allowed in Java 7 but became valid in Java 9. The reader is used to read `./README.md` line by line.

This module helps engineers understand that try-with-resources is not limited to Java 7's original form. If a resource variable is initialized before the try block and never reassigned, Java 9 lets you use it directly in `try (resource)`.

### `var`

**Purpose:** Demonstrates JEP 286 — local variable type inference — which was introduced in Java 10 but is included in this Java 11 showcase collection.

**Key classes:**
- **`Example`** — Exercises `var` across seven common patterns: generic constructor calls, stream return types, `List.of()` factory calls, `Paths.get()`, `Files.readAllBytes()`, enhanced for-loops, and try-with-resources. Each example includes comments explaining the inferred type.

This is a great module for understanding when `var` is idiomatic (when the right-hand side makes the type obvious) and when it should be avoided (when the initializer is uninformative or a lambda).

## Getting Started

If you're exploring this repository for the first time, here is a recommended reading and execution order:

1. **`singlefile/HelloWorld`** — The absolute starting point. Compile and run with a single command (`java HelloWorld.java`). This proves the Java 11 environment works and demonstrates JEP 330.

2. **`var/Example`** — The `var` keyword is used in nearly every other example, so understanding local variable type inference first will make the remaining code easier to follow. Run `Example.main()` to see all seven patterns.

3. **`collections/Example`** — The immutable collection factories (`List.of()`, `Map.of()`, `Set.of()`) appear in many modules. Understanding their behavior (read-only, throw on modification) will prevent surprises.

4. **`string/Example`** — The new String methods (`strip()`, `isBlank()`, `lines()`) are broadly applicable. Each demonstration method is self-contained and can be uncommented and run individually from `main()`.

5. **`files/Example`** — A four-line file I/O demo that shows how much simpler text file operations became in Java 11. Quick to read and easy to run.

6. **`http/Example`** — The most comprehensive module. Read the method-level documentation to understand the different HTTP client capabilities, then uncomment and run `syncGet("https://biezhi.me")` or `asyncPost()` to see them in action.

7. **`interfaces/Example`** — A small interface showing private methods. Read the source; there's no need to run anything special.

8. **`processor/Example`** — Run `main()` to print the current JVM's PID. Then explore the `ProcessHandle` API documentation to see the full set of process management capabilities.

9. **`time/Example`** — Run `main()` to see the duration-to-TimeUnit conversions in action. Useful reference if you work with concurrent timed operations.

10. **`trywithresources/Example`** — Run `main()` to read and print `./README.md`. Demonstrates the Java 9 try-with-resources improvement.

Each example can be run independently — there are no setup steps, no database connections, and no external services required (the `http` module does reach out to real URLs, but those connections are part of the demo, not a prerequisite). If you need to modify any example, the class is a plain `public` class with a `public static void main()` method that you can edit and recompile directly.
