# Io / Github / Biezhi / Java11 / Var

## Overview

This module is a demonstration of [JEP 286](https://openjdk.java.net/jeps/286) — local variable type inference in Java, introduced in Java 10. It lives under the `io.github.biezhi.java11` collection of example modules and shows how the `var` keyword replaces explicit type declarations with compiler-inferred types. The purpose is educational: it walks through the most common and idiomatic `var` usage patterns, including collection instantiation, stream chaining, `List.of()` factory calls, `Paths` and `Files` API interactions, enhanced for-loops, and try-with-resources blocks.

## Key Classes and Interfaces

### [Example](src/main/java/io/github/biezhi/java11/var/Example.java:16)

The `Example` class is the sole class in this subpackage. It serves as a self-contained showcase of `var` local variable type inference across a range of everyday Java patterns. The `main` method exercises seven distinct `var` scenarios.

#### `main(String[] args)` — [lines 18-42](src/main/java/io/github/biezhi/java11/var/Example.java:18)

The single entry point. Declared with `throws Exception` because some of the `var` examples involve checked exceptions. It walks through these demonstrations:

| # | Code | Inferred Type | What It Shows |
|---|------|---------------|---------------|
| 1 | `var list = new ArrayList<String>()` | `ArrayList<String>` | `var` with a generic constructor call — the type parameter carries through. |
| 2 | `var stream = list.stream()` | `Stream<String>` | `var` infers from a method return type. The `String` type parameter is preserved from `list`. |
| 3 | `var newList = List.of("hello", "biezhi")` | `List<String>` | `var` with the `List.of()` static factory (Java 9+). Demonstrates inference from utility methods. |
| 4 | `var path = Paths.get(fileName)` | `Path` | `var` with NIO.2 `Paths.get()`. The compiler resolves to the concrete return type. |
| 5 | `var bytes = Files.readAllBytes(path)` | `byte[]` | `var` with a byte array return type — a less commonly used but perfectly valid inference target. |
| 6 | `for (var b : bytes)` | `byte` (primitive) | `var` inside an enhanced for-loop. The element type of the iterated array is inferred as the primitive `byte`. |
| 7 | `try (var foo = new FileInputStream(...))` | `FileInputStream` | `var` inside a try-with-resources block. Combines Java 10's `var` with the auto-closing contract of try-with-resources. |

Each `var` usage is paired with a Chinese comment explaining that the type is auto-inferred. Notably, the for-each body is left as a `// TODO` placeholder, indicating this is intentionally incomplete and meant as a starting point for exploration.

## How It Works

`var` is a contextual reserved type name introduced by JEP 286. It is not a keyword, so it can still appear in identifiers like `myVar` (though doing so is discouraged). The compiler resolves `var` at each declaration site by examining the initializer expression. The rules are straightforward:

1. **The initializer is required.** `var x;` is a compile error because there is nothing to infer from.
2. **The inferred type becomes the compile-time type.** After `var list = new ArrayList<String>()`, `list` is typed as `ArrayList<String>`, not a more general interface.
3. **`null` cannot be used as an initializer.** `var x = null` fails because the compiler cannot determine a type.
4. **Lambdas and method references cannot be inferred.** A lambda expression does not carry an explicit type, so the compiler cannot resolve `var fn = (a, b) -> a + b`. You must use an explicit type or assign to a functional interface target.

This module does not declare any runtime behavior beyond printing the `byte[]` array reference and the `FileInputStream` object. Its value is entirely in the compile-time type inference patterns it demonstrates.

## Data Model

There are no data model classes in this module. All types involved are standard JDK types (`ArrayList`, `List`, `Stream`, `Path`, `byte[]`, `FileInputStream`). The module does not define any custom DTOs, entities, or value objects.

## Dependencies and Integration

This module has **no package dependencies** beyond the Java Standard Library. It imports:

- `java.io.File` and `java.io.FileInputStream` — for the try-with-resources example
- `java.nio.file.Files` and `java.nio.file.Paths` — for the NIO path/bytes example
- `java.util.ArrayList` and `java.util.List` — for the collection examples

It is part of the broader `io.github.biezhi.java11` monorepo of example modules. Other subpackages (such as [collections](src/main/java/io/github/biezhi/java11/collections/Example.java), [http](src/main/java/io/github/biezhi/java11/http/Example.java), [string](src/main/java/io/github/biezhi/java11/string/Example.java), and [time](src/main/java/io/github/biezhi/java11/time/Example.java)) follow the same `Example` class pattern, each demonstrating a different JDK feature.

## Relationship Diagram

```mermaid
flowchart TD
    subgraph java11_var["io.github.biezhi.java11.var"]
        ex["Example
JEP 286 var local variable type inference demo"]
    end
    ex -->|demonstrates| inferred["var local variable declarations"]
    inferred --> listType["var list = new ArrayList<String>()
-> inferred: ArrayList<String>"]
    inferred --> streamType["var stream = list.stream()
-> inferred: Stream<String>"]
    inferred --> listOf["var newList = List.of(...)
-> inferred: List<String>"]
    inferred --> filePath["var path = Paths.get(...)
-> inferred: Path"]
    inferred --> bytes["var bytes = Files.readAllBytes(path)
-> inferred: byte[]"]
    inferred --> forLoop["var b in for-each
-> inferred: byte (primitive)"]
    inferred --> tryRes["var foo in try-with-resources
-> inferred: FileInputStream"]
```

## Notes for Developers

- **`var` is not a new type.** It is syntactic sugar for type inference. The generated bytecode is identical to writing the full type explicitly.
- **Java 10 feature, not Java 11.** Despite the `java11` package name, JEP 286 was introduced in Java 10. This subpackage is simply part of the Java 11 examples collection.
- **Use cases for `var`.** The most common and widely accepted uses are when the right-hand side makes the type obvious (e.g., `new ArrayList<>()`, `Map.of()`, `Paths.get()`). Avoid `var` when the initializer is uninformative (e.g., `var x = compute()` where `compute()` is a long method name that obscures the return type).
- **For-each limitation.** In `for (var x : collection)`, `x` gets the element type, not an iterator. The compiler resolves this from the `Iterable` or array type.
- **This is a demo-only module.** There are no production classes, no tests, and no configuration. It is designed to be read and modified as a learning aid.
- **The for-each body is a TODO.** The `// TODO` comment on the line following `for (var b : bytes)` signals an intentional incomplete section. A developer extending this example could add meaningful operations there to demonstrate that `b` is indeed a `byte`.
