# Io / Github / Biezhi / Java11

## Overview

The `io.github.biezhi.java11` module is an **educational showcase of new Java language and API features** spanning JDK 9 through JDK 11. It is not a production library or application — rather, it is a curated collection of minimal, self-contained demonstration packages, each dedicated to a single feature area. The project is authored by [biezhi](https://github.com/biezhi) and serves as a practical reference for developers learning or refreshing their knowledge of modern Java idioms.

While the parent package is named `java11` (reflecting its target release of Java 11, LTS), several of the features demonstrated were introduced in earlier versions: private interface methods (Java 9), collection factory methods and `var` type inference (Java 9/10), and try-with-resources improvements (Java 9). The module treats Java 11 as the common baseline and showcases features available in that release regardless of their original introduction version.

## Sub-module Guide

The module is organized into ten sub-packages, each demonstrating a distinct capability. They can be grouped into four conceptual categories:

### Language Features

| Sub-package | Feature | JDK Version |
|---|---|---|
| [`var`](/io/github/biezhi/java11/var) | Local variable type inference (`var`) | 10 (JEP 286) |
| [`interfaces`](/io/github/biezhi/java11/interfaces) | Private methods in interfaces | 9 |
| [`trywithresources`](/io/github/biezhi/java11/trywithresources) | Java SE 9 try-with-resources improvement | 9 |
| [`collections`](/io/github/biezhi/java11/collections) | Diamond operator + collection factory methods | 9 |

These four packages demonstrate how Java evolved its language ergonomics. The `var` sub-package shows how the compiler can infer types from initializer expressions (`var list = new ArrayList<>()`), reducing verbosity without sacrificing type safety. The `interfaces` package demonstrates how Java 9 solved a long-standing problem: default methods in interfaces (introduced in Java 8) could not share logic through private helper methods — Java 9 added `private` methods to interfaces, enabling code reuse between default implementations. The `trywithresources` sub-package shows the Java 9 improvement that allows effectively-final resource variables to be declared *outside* the `try` parentheses, eliminating boilerplate when a resource is prepared before use. The `collections` package brings together two related improvements: the extension of the diamond operator to anonymous inner classes (Java 9), and the immutable collection factory methods (`List.of`, `Map.of`, `Set.of`) introduced in Java 9 as a cleaner alternative to `Arrays.asList` and `Collections.unmodifiableMap`.

**Relationship:** These four form a cohesive language-evolution narrative. `var` reduces noise at declaration sites; private interface methods reduce duplication between default methods; try-with-resources improvements reduce boilerplate around resource management; and the diamond operator extension keeps anonymous inner class syntax concise. Together they illustrate Java's gradual movement toward less boilerplate and more expressive type inference.

### JDK API Additions

| Sub-package | Feature | JDK Version |
|---|---|---|
| [`string`](/io/github/biezhi/java11/string) | `repeat()`, `lines()`, `strip()`, `stripLeading()`, `stripTrailing()`, `isBlank()` | 11 |
| [`time`](/io/github/biezhi/java11/time) | `TimeUnit.convert(Duration)` bridging | 9 |
| [`processor`](/io/github/biezhi/java11/processor) | `ProcessHandle` OS-level process inspection | 9 |

The `string` sub-package demonstrates all six new String methods added in Java 11, covering whitespace handling (`strip`, `isBlank`), multi-line text processing (`lines`), and repetition (`repeat`). The `time` sub-package addresses a practical interoperability gap: while Java 8 brought the modern `java.time` API, concurrent utilities like `ScheduledExecutorService` and `Lock.tryLock()` still rely on `TimeUnit` for timeout parameters. Java 9 added a `TimeUnit.convert(Duration)` overload that bridges the two worlds in a single method call. The `processor` sub-package showcases the `ProcessHandle` API for inspecting and managing OS-level processes — a significant improvement over the older `ProcessBuilder`/`Process` approach.

**Relationship:** These API additions complement each other as utility improvements to the JDK standard library. The String methods handle text processing gaps that developers routinely worked around with regex or external libraries. The `TimeUnit`/`Duration` bridging enables modern time handling in legacy concurrent APIs. The `ProcessHandle` API gives developers programmatic access to the OS process tree — something that previously required native bridges or external tools.

### File and Script I/O

| Sub-package | Feature | JDK Version |
|---|---|---|
| [`files`](/io/github/biezhi/java11/files) | `Files.readString()` and `Files.writeString()` | 11 |
| [`singlefile`](/io/github/biezhi/java11/singlefile) | JEP 330: single-file source execution | 11 |

The `files` sub-package demonstrates the two convenience methods added to `java.nio.file.Files` in Java 11: `readString()` and `writeString()`. Before these methods, reading or writing text files required manual stream management, charset handling, and resource cleanup — even for the simplest operations. The single-file execution package demonstrates JEP 330, which allows `java HelloWorld.java` to compile and run a source file in one step, eliminating the traditional two-step `javac` then `java` workflow.

**Relationship:** Both packages address developer productivity around file and script workflows. `files` simplifies the most common text file operations into single-method calls, while single-file execution eliminates the compilation ceremony for small programs. Together they reflect Java 11's focus on making the language more approachable for scripting, prototyping, and everyday file operations.

### Network and Concurrency

| Sub-package | Feature | JDK Version |
|---|---|---|
| [`http`](/io/github/biezhi/java11/http) | New `java.net.http` client (sync and async) | 11 |

The `http` sub-package is the most substantial in terms of feature breadth. It demonstrates synchronous and asynchronous HTTP requests, file download and upload, proxy configuration, basic authentication, HTTP/2 support, and concurrent batch requests using `CompletableFuture`. The `HttpClient` API replaces the legacy `java.net.URL`-based approach and introduces a fluent builder pattern, non-blocking async operations, and configurable body handlers (`ofString`, `ofFile`, `discarding`).

**Relationship:** The HTTP client is the only sub-package dealing with network communication. Its async patterns (`sendAsync` + `CompletableFuture`) conceptually connect to the broader theme of concurrency improvements in Java 9/11, though no other sub-package directly uses `CompletableFuture`.

## How the Sub-modules Interact

Although each sub-package is self-contained (there are no cross-package imports), they share a common design pattern and serve a unified purpose. The following diagram shows how they relate conceptually:

```mermaid
flowchart LR
    Java11["Java11 Module<br/>io.github.biezhi.java11"]

    Java11 --> Collections["collections"]
    Java11 --> Files["files"]
    Java11 --> Http["http"]
    Java11 --> Interfaces["interfaces"]
    Java11 --> Processor["processor"]
    Java11 --> Singlefile["singlefile"]
    Java11 --> String["string"]
    Java11 --> Time["time"]
    Java11 --> TryWithResources["trywithresources"]
    Java11 --> Var["var"]

    Collections --> Factory["Collection factory methods<br/>List.of, Map.of, Set.of"]
    Collections --> Diamond["Diamond operator<br/>anonymous inner classes"]

    Files --> ReadWrite["Files.readString / writeString"]

    Http --> HttpClient["HttpClient<br/>sync + async requests"]
    Http --> Auth["Proxy, Auth, HTTP/2"]

    Interfaces --> Private["Private interface methods"]

    Processor --> ProcessHandle["ProcessHandle<br/>OS process inspection"]

    Singlefile --> JEP330["JEP 330<br/>single-file execution"]

    String --> NewStringMethods["String.repeat / lines / strip / isBlank"]

    Time --> Duration["Duration / TimeUnit conversion"]

    TryWithResources --> AutoClose["Try-with-resources<br/>Java SE 9 improvement"]

    Var --> TypeInference["var local variable<br/>type inference"]
```

Each sub-package follows the same structural pattern: a single `Example` class with a `main` method, designed to be run directly and produce console output that demonstrates the feature in action. This consistency makes the module easy to navigate — any developer can open any `Example.java` and immediately understand its purpose.

A second view shows how features group by their functional domain:

```mermaid
flowchart TD
    subgraph Language["Language Features"]
        Var["var type inference"]
        Interfaces["Private interface methods"]
        TryWithResources["Try-with-resources improvement"]
        Diamond["Diamond operator on anonymous classes"]
    end

    subgraph APIs["JDK API Additions"]
        NewString["New String methods"]
        FactoryMethods["Collection factory methods"]
        TimeAPI["Duration-TimeUnit bridging"]
        ProcessAPI["ProcessHandle improvements"]
        NewHttpClient["New HttpClient"]
    end

    subgraph IO["File and Script I/O"]
        FilesIO["Files.readString/writeString"]
        Singlefile["Single-file source execution"]
    end

    subgraph Execution["Execution Model"]
        JEP330["JEP 330: java <source>"]
        AsyncIO["Async request pipeline<br/>sendAsync + CompletableFuture"]
    end

    Var --> APIs
    Interfaces --> Language
    TryWithResources --> Language
    Diamond --> Language
    APIs --> Execution
    FilesIO --> Execution
    Singlefile --> Execution
    NewHttpClient --> Execution
```

## Key Patterns and Architecture

### Uniform Example Pattern

Every sub-package follows the same convention:

1. **Class name:** `Example` (with a few exceptions like `DiamondOperatorExample` in the `collections` package and `Foo` in the `http` package).
2. **Method:** A single `public static void main(String[] args)` that demonstrates one or more features.
3. **Output:** Console-printed results that a developer can visually verify.
4. **Scope:** Self-contained with no cross-package dependencies.

This uniformity is intentional — the module is designed for readability, not reusability. Each `main` method is a copy-paste-able example that can be extracted into production code if needed, but the examples themselves are not meant to be reused as-is.

### Type Inference as a Cross-Cutting Theme

The `var` sub-package introduces local variable type inference, but this theme appears throughout the module. Collection factory methods (`List.of`, `Map.of`) pair naturally with `var` to eliminate verbose type declarations. The `collections` package explicitly demonstrates this pairing. Similarly, the NIO.2 examples in the `var` package (`Paths.get()`, `Files.readAllBytes()`) show how `var` keeps file I/O code clean. This suggests an implicit design philosophy: modern Java features should be used together to maximize expressiveness while minimizing boilerplate.

### Immutable-by-Default Collections

The `collections` package uses factory methods that return immutable collections. This is an important architectural note: Java 9 shifted the default collection creation pattern from mutable (`new ArrayList<>()`) to immutable (`List.of()`). Developers should be aware that any code adapted from these examples needs wrapping (`new ArrayList<>(List.of(...))`) if mutation is required. This pattern extends to `Map.entry()` and `Set.of()`, all of which produce immutable results.

### Async Request Pipeline

The `http` package demonstrates a pattern that is likely the most valuable for production adaptation: the async HTTP client pipeline using `CompletableFuture`. The pattern of `sendAsync(...)` followed by `whenComplete(...)` and `join()` can be adapted for real applications. However, the examples all block on `.join()`, so they do not represent true non-blocking usage — production code would return the `CompletableFuture` to the caller rather than blocking.

### Single-File vs Full Compilation

The `singlefile` package (JEP 330) and the `files` package represent two sides of the same coin: simplifying Java as a scripting language. Single-file execution removes the need for a build step for small programs, while `Files.readString`/`writeString` remove the need for manual stream management for simple file operations. Together they suggest that Java 11 was targeting developers who wanted to write quick scripts in Java without the overhead of project setup.

## Dependencies and Integration

### External Dependencies

| Dependency | Sub-package(s) | Purpose |
|---|---|---|
| `com.google.gson.Gson` | `http` | JSON serialization of `Foo` objects for POST body |

All other dependencies are JDK standard library classes. No third-party libraries are used elsewhere in the module.

### JDK Standard Library Usage

The module exercises a broad slice of the JDK:

- `java.util.List`, `java.util.Map`, `java.util.Set` — collection factory methods
- `java.nio.file.Files`, `java.nio.file.Paths` — file I/O
- `java.net.http.HttpClient`, `java.net.http.HttpRequest`, `java.net.http.HttpResponse` — HTTP client
- `java.lang.ProcessHandle` — OS process inspection
- `java.lang.String` — new string methods
- `java.time.Duration`, `java.util.concurrent.TimeUnit` — time bridging
- `java.io.BufferedReader`, `java.io.FileReader` — try-with-resources demo
- `java.io.FileInputStream`, `java.io.File` — var with I/O demo

### Cross-Module Relationships

No cross-module relationships were detected in the index. Each sub-package is fully independent. Nothing in the project depends on these example packages, and they do not import from each other. The module is a leaf-level collection with no child modules.

## Notes for Developers

### Educational Purpose

This is a demonstration repository, not production code. All classes are `Example` with `main` methods and no external visibility. Treat every example as learning material — useful patterns can be adapted, but the code itself should not be copied into production.

### Java Version Requirements

The module requires at least Java 11 to compile and run. However, several features demonstrated were introduced in earlier JDKs (Java 9 or 10). The `java11` package name reflects the common baseline, not the introduction version of every feature.

### HttpClient Reuse

The `http` package creates a new `HttpClient` instance for every example method. In production code, `HttpClient` is thread-safe and designed to be reused. Create one shared instance and call `send`/`sendAsync` repeatedly.

### Immutable Collections

Factory methods from the `collections` package return immutable collections. Any attempt to mutate them throws `UnsupportedOperationException`. Wrap with mutable constructors if modification is needed.

### Try-with-Resources Variants

The `trywithresources` package demonstrates the Java 9 improvement (declaring resources outside the try block). The more common Java 7 style — declaring the resource inside the try parentheses — is equally valid and arguably more common in production code.

### Commented-Out `main()` Calls

The `string` package's `main()` method currently has all demonstration calls commented out except `lines()`. To test individual features, uncomment the relevant line before running.

### UTF-8 Assumption

The `files` package's `Files.readString()` and `Files.writeString()` use UTF-8 encoding by default. If you need a different encoding, use the overloaded variants that accept a `Charset` parameter.

### Single-File Limitations

JEP 330 (single-file execution) supports at most one public top-level class per source file. Third-party library dependencies require explicit `--class-path` or `--module-path` flags on the `java` command.

### Author Context

The source was authored by **biezhi** starting in 2018, shortly after Java 11's release in March 2018. Many examples were written as learning exercises shortly after the features became available, making them early practical demonstrations of Java 11 capabilities.
