//! The javars language-reference corpus.
//!
//! One entry per name the current javars build actually implements, as
//! `(name, chapter, signature, doc, example)`. This is the single source of
//! truth for three consumers:
//!
//! * the LSP completion and hover providers ([`crate::lsp`]),
//! * the offline `docs/reference.html` generator (`src/bin/gen_docs.rs`),
//! * and, by construction, the claim that the editor tooling and the published
//! reference never drift from the runtime.
//!
//! Every entry is written from the implementation it documents, and each chapter
//! names the table it was read from:
//!
//! | Chapter | Source of truth |
//! | --- | --- |
//! | Keywords | `lexer.rs` `keyword_or_ident` |
//! | Contextual Keywords | `parser.rs` (identifier-matched words) |
//! | Literals | `lexer.rs` `lex` |
//! | Types | `compiler.rs` `numeric_rank` / `is_reference_type` |
//! | Operators | `lexer.rs` `Tok`, `ast.rs` `BinOp` / `UnOp` |
//! | Console IO | `host.rs` `JPRINTLN` / `JPRINT` / `JEPRINTLN` / `JEPRINT` |
//! | String Methods | `host.rs` `string_method` |
//! | Static Library | `host.rs` `static_method` |
//! | Collection Types | `compiler.rs` `collection_kind` / `is_concrete_collection` |
//! | Collection Statics | `host.rs` `collection_static` |
//! | List / Map / Set Methods | `host.rs` `list_method` / `map_method` / `set_method` |
//! | Throwables | `prelude.rs` `THROWABLES` |
//! | Functional Interfaces | `prelude.rs` `FUNCTIONAL` |
//! | Class Members | `parser.rs` `enum_members` / `record_members`, `compiler.rs` |
//! | Method References | `compiler.rs` `desugar_method_ref` / `type_method_ref` |
//! | Format Conversions | `host.rs` `java_format` / `format_conversion` |
//! | Runtime Builtins | `host.rs` `install` / `install_debug` |
//!
//! Where javars computes something other than `java` does, the entry says so.
/// A reference entry: `(name, chapter, signature, doc, example)`. An empty
/// `example` renders as signature + description only.
pub type Entry = (
&'static str,
&'static str,
&'static str,
&'static str,
&'static str,
);
/// The reference corpus, grouped by chapter in emission order.
pub const REFERENCE: &[Entry] = &[
// ── Keywords: the 18 reserved words in `lexer.rs` `keyword_or_ident` ──
(
"class",
"Keywords",
"[modifiers] class Name [extends Base] [implements I, J] { members }",
"Declares a class. Every class in a compilation unit — top-level siblings and nested `static` classes alike — is flattened into one namespace, so a nested class is referred to by its bare name. javars runs the `main` of whichever class declares `public static void main(String[] args)`.",
"public class Main { public static void main(String[] args) { System.out.println(\"hi\"); } }",
),
(
"public",
"Keywords",
"public <member or type declaration>",
"Access modifier. javars parses every access modifier and enforces none — visibility is a `javac` check, and a program that reaches javars has already passed it. Required spelling on the entry class and its `main`.",
"public static void main(String[] args) { }",
),
(
"static",
"Keywords",
"static <field, method, initializer block, or nested class>",
"Marks a class-level member. Static fields become chunk globals seeded with their type default; `static { … }` blocks run at class-initialization time in textual order with the static field initializers. Required on `main`.",
"class Counter { static int n = 0; static { n = 10; } static int bump() { return ++n; } }",
),
(
"void",
"Keywords",
"void method(params)",
"Declares a method with no return value. A bare `return;` leaves it early; `return <value>;` from `void main` is a compile error.",
"static void greet() { System.out.println(\"hi\"); return; }",
),
(
"if",
"Keywords",
"if (cond) stmt-or-block [else stmt-or-block]",
"Conditional branch. The condition is lowered to `Op::JumpIfFalse` over the `then` block, so a false test costs one jump and no allocation.",
"if (x > 0) { System.out.println(\"pos\"); } else { System.out.println(\"non-pos\"); }",
),
(
"else",
"Keywords",
"else stmt-or-block",
"The fallback branch of an `if`. Chains as `else if` by nesting, exactly as in Java.",
"if (n == 0) { } else if (n == 1) { } else { System.out.println(\"many\"); }",
),
(
"while",
"Keywords",
"while (cond) stmt-or-block",
"Pre-tested loop: the condition is evaluated before each iteration, including the first. Owns a break scope, so an unlabeled `break`/`continue` inside it targets this loop.",
"int i = 0; while (i < 3) { System.out.println(i); i++; }",
),
(
"for",
"Keywords",
"for (init; cond; update) body | for (T x : iterable) body",
"Both loop forms. The C-style form declares its own scope for the init clause; the enhanced form walks an array directly, or a collection the way a Java iterator does: a `List` is read live, a structural modification of the collection (or of the map behind a `keySet()`/`values()`/`entrySet()`) is `ConcurrentModificationException` at the next element, and the binding is fresh per iteration so a lambda written in the body captures that iteration's value.",
"for (int i = 0; i < 3; i++) { System.out.println(i); }\nfor (String s : names) { System.out.println(s); }",
),
(
"do",
"Keywords",
"do body while (cond);",
"Post-tested loop: the body always runs at least once, then repeats while the condition holds.",
"int i = 0; do { i += 2; } while (i < 5); // i == 6",
),
(
"switch",
"Keywords",
"switch (sel) { case L: … } | switch (sel) { case L -> … } | T v = switch (sel) { … };",
"Multi-way branch in both Java forms. The classic form falls through between groups until a `break`; the arrow form does not fall through and works as a statement or as an expression. The selector may be an `int`, a `String`, or an `enum` constant. Pattern labels, `case null`, and `when` guards are not implemented.",
"String r = switch (n) { case 1 -> \"one\"; case 2, 3 -> \"few\"; default -> \"many\"; };",
),
(
"case",
"Keywords",
"case L: | case L1, L2 ->",
"A `switch` label. In the classic form a matched label runs on into the following groups until a `break` or the end of the switch; in the arrow form one label list selects exactly one arm. Multiple labels per arm are supported in both forms.",
"switch (n) { case 1: System.out.println(\"one\"); break; case 2: case 3: System.out.println(\"few\"); break; }",
),
(
"default",
"Keywords",
"default: | default -> | default T m(params) { … }",
"The `switch` label taken when no `case` matches, and — in an interface body — the modifier that gives a method an inherited implementation. Both spellings lex to the same reserved word; the parser tells them apart by position.",
"switch (n) { default: System.out.println(\"other\"); }\ninterface Shape { int area(); default String describe() { return \"area \" + area(); } }",
),
(
"return",
"Keywords",
"return; | return expr;",
"Leaves the current method, lowering to `Op::ReturnValue` (with `null` pushed for the bare form). Returning a value from `void main` is rejected at compile time.",
"static int max(int a, int b) { if (a > b) return a; return b; }",
),
(
"break",
"Keywords",
"break; | break label;",
"Exits the nearest enclosing loop or `switch`, or the one named by a label. The jump is backpatched once the enclosing construct's end address is known, so a labeled break out of nested loops is a single unconditional jump.",
"outer: for (int i = 0; ; i++) { for (int j = 0; ; j++) { if (i + j > 4) break outer; } }",
),
(
"continue",
"Keywords",
"continue; | continue label;",
"Skips to the next iteration of the nearest enclosing loop, or of the one named by a label. In a C-style `for` the jump lands on the update clause, not on the condition.",
"for (int i = 0; i < 5; i++) { if (i % 2 == 0) continue; System.out.println(i); }",
),
(
"true",
"Keywords",
"true",
"The boolean literal true. Lowers to `Op::LoadTrue`, and prints as `true` rather than fusevm's shell-flavoured `1`.",
"boolean ok = true; System.out.println(ok); // true",
),
(
"false",
"Keywords",
"false",
"The boolean literal false. Lowers to `Op::LoadFalse`, and prints as `false`.",
"boolean done = false; System.out.println(done); // false",
),
(
"new",
"Keywords",
"new C(args) | new T[n] | new T[m][n] | new T[]{ … } | new ArrayList<>()",
"Allocation. A class instance goes through the `JNEW` builtin and then the field initializers and the selected constructor; an array through `JARRAY_NEW`/`JARRAY_NEW_MULTI`; a modeled `java.util` implementation through `JCOLL_NEW`. Every result is an opaque `Value::Obj` handle into the host heap, so assignment aliases by reference. `new I() { … }` / `new C(args) { … }` is an anonymous class: a body that is one method of an interface is the lambda it abbreviates, and any other body is lifted to the class `javac` emits (`Encloser$N`), which forwards `args` to `super(…)` and captures the enclosing locals it reads.",
"Point p = new Point(1, 2);\nint[][] grid = new int[2][3];\nList<String> xs = new ArrayList<>();",
),
// ── Contextual Keywords: words the lexer produces as `Tok::Ident` and the
// parser recognizes by position. They are NOT reserved: a variable named
// `record` or `yield` still lexes as an ordinary identifier.
(
"package",
"Contextual Keywords",
"package name.of.pkg;",
"Accepted and discarded. javars has one flat namespace and no class path, so a package declaration carries no meaning; the parser skips the prologue line so real Java sources compile unchanged.",
"package com.example.demo;",
),
(
"import",
"Contextual Keywords",
"import name.of.Type; | import name.of.pkg.*;",
"Accepted and discarded, like `package`. The modeled library types (`Math`, `ArrayList`, the throwables, the functional interfaces) are always in scope, so no import is needed — and a fully-qualified use such as `java.util.Arrays.toString(a)` is *not* supported, because the qualifier parses as field access on an undefined variable.",
"import java.util.*; // accepted; Arrays, List and friends are in scope regardless",
),
(
"interface",
"Contextual Keywords",
"interface Name [extends I, J] { abstract and default methods }",
"Declares an interface. Abstract methods, `default` bodies, multiple `implements`, and `interface extends` all work; a field is the implicit `public static final` constant JLS 9.3 makes it, read as `Name.FIELD` or bare inside the interface and its implementors; an interface with exactly one abstract method is automatically a lambda target with no registration anywhere.",
"interface Shape { int area(); default String describe() { return \"area \" + area(); } }",
),
(
"enum",
"Contextual Keywords",
"enum Name [implements I] { A, B(args), C { body } ; members }",
"Declares an enum. Constants become singleton instances held in chunk globals, each carrying a synthesized name and ordinal; per-constant arguments and per-constant bodies (which compile to an anonymous subclass) are supported, as is `implements`.",
"enum Op { PLUS { int apply(int a, int b) { return a + b; } }; int apply(int a, int b) { return 0; } }",
),
(
"record",
"Contextual Keywords",
"record Name(T c1, U c2) { [compact constructor] [members] }",
"Declares a record. The parser synthesizes the canonical constructor, one accessor per component, `toString()` in Java's `Name[c1=v1, c2=v2]` form, a component-wise `equals(Object)` guarded by an `instanceof` test, and `hashCode()` as the `31 * h + componentHash` fold — each component through its own wrapper's `hashCode(x)`, so the widths stay apart. Declaring any of them yourself wins over the derived one.",
"record Point(int x, int y) { }\n// new Point(1, 2) prints as Point[x=1, y=2]",
),
(
"extends",
"Contextual Keywords",
"class C extends Base | interface I extends J, K | <T extends Bound>",
"Names a superclass, a set of super-interfaces, or a type-parameter bound. The superclass link drives `instanceof`, the virtual-dispatch chain, and `super(...)` constructor chaining; a bound is erased and dropped.",
"class Dog extends Animal { }",
),
(
"implements",
"Contextual Keywords",
"class C implements I, J",
"Names the interfaces a class implements. Each becomes a supertype edge, so `instanceof I` succeeds and a `default` method of `I` is inherited unless the class overrides it.",
"class Sq implements Shape { public int area() { return 4; } }",
),
(
"abstract",
"Contextual Keywords",
"abstract class C { abstract T m(params); }",
"Marks a class that is never instantiated and a method that has no body. An abstract method contributes its name to the dispatch chain; a concrete subclass supplies the body.",
"abstract class Base { abstract String tag(); }\nclass Impl extends Base { String tag() { return \"impl\"; } }",
),
(
"final",
"Contextual Keywords",
"final <local, parameter, catch parameter, resource, field, or class>",
"Parsed everywhere Java allows it and then dropped. Immutability is a `javac` check that has already run, and javars's lambda capture is a by-value snapshot, so a `final` local and an effectively-final one compile identically.",
"final int limit = 10;\nfor (final String s : names) { System.out.println(s); }",
),
(
"private",
"Contextual Keywords",
"private <member>",
"Parsed and dropped, like every access modifier. javars enforces no visibility.",
"class Box { private int n; private int get() { return n; } }",
),
(
"protected",
"Contextual Keywords",
"protected <member>",
"Parsed and dropped, like every access modifier.",
"class Base { protected String tag() { return \"base\"; } }",
),
(
"synchronized",
"Contextual Keywords",
"synchronized <method> | synchronized (monitor) { … }",
"javars runs a program on one thread, so there is no monitor to acquire: as a method modifier it is dropped. As a *statement* the rest of the semantics still hold — the monitor expression is evaluated exactly once, and a `null` monitor throws `NullPointerException` before the body runs.",
"static synchronized void once() { System.out.println(\"once\"); }\nObject lock = new Object();\nsynchronized (lock) { System.out.println(\"critical\"); }",
),
(
"native",
"Contextual Keywords",
"native <method>",
"Accepted as a method modifier and dropped. javars's own foreign-function path is the inline `rust { … }` block, not JNI.",
"static native void jni(); // accepted as a modifier; there is no JNI binding",
),
(
"volatile",
"Contextual Keywords",
"volatile <field>",
"Accepted as a field modifier and dropped — single-threaded execution gives it nothing to order.",
"class Flag { volatile boolean set; }",
),
(
"transient",
"Contextual Keywords",
"transient <field>",
"Accepted as a field modifier and dropped. javars has no serialization.",
"class Cache { transient int hits; }",
),
(
"throws",
"Contextual Keywords",
"T method(params) throws E1, E2",
"Parsed and discarded. javars performs no checked-exception analysis, so the clause is documentation; a method that throws without declaring it runs identically.",
"static int parse(String s) throws Exception { return Integer.parseInt(s); }",
),
(
"throw",
"Contextual Keywords",
"throw expr;",
"Raises a throwable. The value is parked as the host's pending exception by the `JTHROW` builtin and the compiler jumps to the innermost handler in the frame — or returns out of the frame, so the caller's post-call check sees it and repeats. There is no unwind opcode in fusevm; this is how the unwind is modeled.",
"throw new IllegalStateException(\"bad state\");",
),
(
"try",
"Contextual Keywords",
"try { … } catch (E e) { … } finally { … } | try (R r = new R()) { … }",
"Guards a block. The value-stack depth is recorded on entry so a handler can discard the operands of the expression the throw abandoned. A `try` must carry at least one `catch` or a `finally`. The resource form is desugared in the parser into a `finally` that calls `close()` on each resource in reverse order.",
"try (Res r = new Res()) { use(r); } catch (Exception e) { System.out.println(e); }",
),
(
"catch",
"Contextual Keywords",
"catch (E e) { … } | catch (final E e) { … }",
"Handles a pending throwable whose runtime class is `E` or a subclass — the same supertype walk `instanceof` uses. Arms are tested in source order. A multi-catch (`catch (A | B e)`) lists alternative types before the one bound variable; its alternatives are tested in order and share the one body, and the variable's static type is the first of them (Java uses their least upper bound, which javars does not compute).",
"catch (NumberFormatException e) { System.out.println(e.getMessage()); }",
),
(
"finally",
"Contextual Keywords",
"finally { … }",
"A block emitted on both the normal and the exceptional path out of a `try`, and the target the try-with-resources desugar uses for `close()`.",
"try { work(); } finally { System.out.println(\"always\"); }",
),
(
"instanceof",
"Contextual Keywords",
"expr instanceof Type",
"Runtime type test through the `JINSTANCEOF` builtin, over every shape the value model names: a user class or interface walks the declared supertype graph, a boxed primitive answers its wrapper plus `Number`/`Comparable`/`Serializable`, a collection answers its concrete kind and the `java.util` interfaces above it, an array is `Cloneable` and `Serializable`, an `enum` is an `Enum` and a `record` a `Record`. Every non-null reference is an `Object`; `null` is an instance of nothing, including `Object`. A lambda answers only `Object` (the closure does not record its functional interface), and pattern binding (`x instanceof Point p`) is not implemented.",
"if (shape instanceof Sq) { System.out.println(\"square\"); }",
),
(
"this",
"Contextual Keywords",
"this | this.field | this.method(args) | this::method",
"The receiver of the enclosing instance method or constructor, held in call-frame slot 0. A bare field name that is not a local resolves to `this.name` implicitly. Using `this` outside an instance method is a compile error. `this(...)` as the first statement of a constructor delegates to another constructor of the same class, which is what runs the `super()` chain and the instance initializers — so they run exactly once.",
"class Point { int x; Point(int x) { this.x = x; } int get() { return x; } }",
),
(
"super",
"Contextual Keywords",
"super(args); super.method(args); super.field",
"Three forms. `super(args)` is explicit superclass constructor chaining: every field in the chain is already seeded with its type default when the call runs, so the parent constructor executes on the same receiver — running its *own* instance initializers before its body, per JLS 12.5, which is why a virtual call it makes sees the subclass's fields still at their defaults. `super.method(args)` is a **non-virtual** call to the implementation the enclosing class inherits — resolution starts at the declaring class's superclass, never at the receiver's runtime class, which is what lets an override call the version it overrides without recursing; overload selection, varargs packing and a walk past a parent that does not declare the method all happen at that superclass. Everything inside the body it reaches still dispatches virtually, so a `super.m()` whose callee calls an unqualified `n()` reaches the subclass's `n`. `super.field` is the same field cell `this.field` names (javars merges a class's fields with its ancestors', so field *hiding* is not modeled — see BUGS.md). When no user class up the chain declares the member, `super.toString`/`equals`/`hashCode` answer `java.lang.Object`'s.",
"class Cat extends Animal { public String toString() { return \"Cat/\" + super.toString(); } }",
),
(
"yield",
"Contextual Keywords",
"yield expr;",
"Supplies the value of a block-bodied arm of a `switch` *expression*. Recognized only while a switch expression is being parsed, so `yield` remains a usable identifier everywhere else.",
"int n = switch (k) { case 1 -> 10; default -> { int t = k * 2; yield t; } };",
),
(
"assert",
"Contextual Keywords",
"assert cond; | assert cond : detail;",
"Parsed and compiled to nothing: the reference launcher runs with assertions disabled unless `-ea` is given, and a disabled assertion evaluates neither the condition nor the detail, so neither does javars.",
"int x = 0;\nassert (x = 5) > 0;\nSystem.out.println(x); // 0",
),
(
"null",
"Contextual Keywords",
"null",
"The null reference. javars models it as `Value::Undef` — the value an unassigned fusevm slot already holds — so `null` needs no keyword: it lexes as an identifier that was never assigned. It prints as `null`, compares equal to itself under `==`, and dereferencing it raises the matching NullPointerException.",
"String s = null;\nSystem.out.println(s + \" \" + (s == null)); // null true",
),
// ── Literals: the forms `lexer.rs` `lex` produces ──
(
"int literal",
"Literals",
"0 42 2147483647",
"A decimal integer literal. Arithmetic on two statically `int`-width operands wraps at 32 bits, which the compiler emits as a native shift pair rather than a builtin so the JIT can still trace it. There are no hex, binary, or octal literals and no `_` digit separators: `0x10` lexes as `0` followed by the identifier `x10`.",
"int big = 2147483647;\nSystem.out.println(big + 1); // -2147483648",
),
(
"long literal",
"Literals",
"0L 9000000000L 42l",
"An `L`/`l`-suffixed integer literal. The suffix survives lexing as its own token kind because it is what types the value `long` and therefore exempts it from the 32-bit `int` wrap.",
"long big = 2147483647L;\nSystem.out.println(big + 1); // 2147483648",
),
(
"double literal",
"Literals",
"3.0 1.5d 2D",
"A floating-point literal: any literal with a fractional part, an exponent, or a `d`/`D`/`f`/`F` suffix. It prints through Java's `Double.toString` rules — a trailing `.0` on whole values, `Infinity`/`NaN` for the non-finite ones.",
"double d = 3.0;\nSystem.out.println(d); // 3.0",
),
(
"float literal",
"Literals",
"1.5f 2F",
"An `f`/`F`-suffixed literal. javars has one floating kind (`f64`), so the suffix only marks the literal as floating; it does not narrow the value to 32-bit precision the way `javac` does.",
"float f = 1.5f;\nSystem.out.println(f); // 1.5",
),
(
"exponent literal",
"Literals",
"1e3 1.5e-3 2E+2",
"Scientific notation, with or without a fractional part; either way the literal is floating point. The `e` is consumed only when a valid exponent follows, so `1.foo` and an identifier beginning with `e` are left alone. Values outside `[1e-3, 1e7)` print in Java's uppercase scientific form.",
"System.out.println(1e3); // 1000.0\nSystem.out.println(25000000.0); // 2.5E7",
),
(
"string literal",
"Literals",
"\"text\"",
"A double-quoted string. Multi-byte characters are decoded as full UTF-8 scalars, so a non-ASCII literal survives lexing intact. Text blocks (`\"\"\"`) are not implemented.",
"String s = \"hello\";",
),
(
"char literal",
"Literals",
"'c' '\\n'",
"A single-quoted character, modeled as a one-character *string* rather than an integer. That is javars's one deliberate `char` divergence: `'A' + 1` concatenates to `\"A1\"` where Java's numeric promotion gives `66`.",
"char c = 'A';\nSystem.out.println(c + 1); // A1 (Java prints 66)",
),
(
"escape sequence",
"Literals",
"\\n \\t \\r \\0 \\\\ \\\" \\'",
"The escapes the lexer decodes inside a string or char literal. Any other escaped character passes through as itself, so `\\q` is a literal `q`. Unicode escapes (`\\uXXXX`) are not decoded.",
"System.out.println(\"a\\tb\\nc\");",
),
(
"array initializer",
"Literals",
"{ e0, e1, … } | new T[]{ e0, e1, … }",
"An array literal. Elements are evaluated left to right and handed to the `JARRAY_LIT` builtin, which allocates one heap array. Nested braces build a rectangular multi-dimensional array.",
"int[] a = {1, 2, 3};\nint[][] g = {{1, 2}, {3, 4}};",
),
(
"multi-declarator declaration",
"Types",
"T a [= e], b [= e], …; | T a[] = { … }, b;",
"One declaration statement declaring several variables — as a local, in a `for` init clause, or as a field. Declarators run left to right, so a later initializer may read an earlier name, and any may be left uninitialized. A C-style array suffix binds to its own *declarator*, so `int p[] = {1}, q;` is an `int[]` and an `int`; the suffix is accepted on locals, fields, and parameters. `var` is rejected here, as it is by `javac`.",
"int a = 1, b = a + 1, c;\nint p[] = {4, 5}, q = 6;\nfor (int i = 0, n = 3; i < n; i++) { System.out.println(i); }",
),
// ── Types: declaration-position type names with runtime meaning ──
(
"int",
"Types",
"int name [= expr];",
"32-bit integer declaration. Arithmetic between two `int`-width operands wraps at 32 bits, matching `javac`; compound assignment and `++` narrow back to `int` on store.",
"int n = 42;",
),
(
"long",
"Types",
"long name [= expr];",
"64-bit integer declaration. A `long` operand suppresses the 32-bit wrap, so the arithmetic runs at fusevm's native `i64` width.",
"long big = 9000000000L;",
),
(
"short",
"Types",
"short name [= expr];",
"16-bit integer declaration. Java promotes `short` to `int` before any binary operation, so javars treats it as `int`-width for the wrap decision and never narrows the stored value to 16 bits.",
"short s = 7;",
),
(
"byte",
"Types",
"byte name [= expr];",
"8-bit integer declaration. Like `short`, it promotes to `int` for arithmetic and is not narrowed on store.",
"byte b = 1;",
),
(
"double",
"Types",
"double name [= expr];",
"64-bit floating-point declaration — javars's only floating kind. Division follows IEEE-754 through the `JDIV` builtin, so a zero divisor yields a signed infinity or NaN instead of faulting.",
"double d = 3.0;\nSystem.out.println(d); // 3.0",
),
(
"float",
"Types",
"float name [= expr];",
"Java's 32-bit floating-point type, kept at 32 bits rather than aliased to `double`: every operation rounds *once* at 32 bits (on the host, so it cannot round twice), and the value prints as the shortest decimal that round-trips at 32 bits. `Float.MIN_VALUE` prints `1.4E-45` — the two-digit widening Java's `toString` specification applies whenever the shortest form has a single digit.",
"float f = 1.5f;\nSystem.out.println(1.0f / 3.0f); // 0.33333334",
),
(
"boolean",
"Types",
"boolean name [= expr];",
"Boolean declaration. Prints as `true`/`false` through the Java-formatting print builtins rather than fusevm's shell-flavoured `1`/`0`.",
"boolean ok = true;",
),
(
"char",
"Types",
"char name [= expr];",
"Character declaration. A `char` value is a one-character string, so `+` concatenates rather than promoting to `int`, and a `char` is one UTF-16 code unit, so a character above the BMP is two of them.",
"char c = 'A';",
),
(
"String",
"Types",
"String name [= expr];",
"String declaration, and the receiver type that routes an instance call to the `java.lang.String` methods. `+` with a `String` operand concatenates through the host numeric hook using Java's value-to-string rules.",
"String s = \"hi \" + 1 + 2; // \"hi 12\"",
),
(
"var",
"Types",
"var name = expr;",
"Local variable with an inferred type (Java 10+). The inferred type is *recorded*, not just the value, so a `var` participates in `/`-truncation, the 32-bit `int` wrap, and class-typed dispatch exactly as the explicit spelling would. `var a = 1, b = 2;` is rejected, as it is by `javac`: each declarator would need its own inference.",
"var s = \"inferred\";\nvar i = 7; System.out.println(i / 2); // 3, not 3.5",
),
(
"Object",
"Types",
"Object name [= expr]; | new Object()",
"The universal reference type, and the erasure of every generic type parameter. Any reference is assignable to it (at a deliberately high overload-resolution cost, so a more specific overload always wins), and a `String` satisfies it. `new Object()` allocates the fieldless root instance — a distinct identity per allocation, usable as a lock, a sentinel, or a map key — and the methods a class inherits without overriding answer from `Object`: `equals` is reference identity, `getClass().getName()` is `java.lang.Object`, `toString()` is `java.lang.Object@<hash>`.",
"Object o = \"anything\";\nObject lock = new Object();\nSystem.out.println(lock.equals(lock)); // true",
),
(
"T[]",
"Types",
"T[] name [= expr]; | T name[]; | T[][] name;",
"An array type. Arrays are host heap objects with reference (aliasing) assignment, a `.length` field, and a bounds check on every access that raises Java's `ArrayIndexOutOfBoundsException` with its exact detail message.",
"int[] a = new int[3];\nString[][] grid = new String[2][2];",
),
// ── Operators: `lexer.rs` `Tok` plus `ast.rs` `BinOp`/`UnOp` ──
(
"+",
"Operators",
"a + b",
"Addition when both operands are numeric, string concatenation when either is not. The concatenating path runs in the host's strict numeric hook and renders both sides with Java's `String.valueOf` rules, so `true`, `3.0`, and `null` all print the way `java` prints them.",
"System.out.println(1 + 2); // 3\nSystem.out.println(\"n=\" + 3.0); // n=3.0",
),
(
"-",
"Operators",
"a - b",
"Subtraction. A non-numeric operand is a type error in Java, so javars reports it rather than coercing: `\"a\" - 1` is a run-time `operator `Sub` is not defined` error, not a silent zero.",
"System.out.println(5 - 2); // 3",
),
(
"*",
"Operators",
"a * b",
"Multiplication, wrapping at 32 bits when both operands are statically `int`-width.",
"System.out.println(6 * 7); // 42",
),
(
"/",
"Operators",
"a / b",
"Division. Statically-integral division stays on fusevm's native op — so the JIT can trace it — and a zero divisor raises `ArithmeticException: / by zero`. A floating operand routes to the `JDIV` builtin instead, where IEEE-754 gives a signed infinity or NaN and never faults.",
"System.out.println(7 / 2); // 3\nSystem.out.println(7.0 / 0.0); // Infinity",
),
(
"%",
"Operators",
"a % b",
"Remainder, taking the sign of the dividend exactly as Java does.",
"System.out.println(-7 % 3); // -1",
),
(
"unary -",
"Operators",
"-a",
"Arithmetic negation, lowered to `Op::Negate`. Applying it to a non-numeric value is reported as a type error rather than coerced.",
"int n = -5;",
),
(
"unary +",
"Operators",
"+a",
"Changes no bits, but it is not a no-op: JLS 5.6.1 applies unary numeric promotion, so a `byte`, `short` or `char` operand becomes an `int`. For `char` that is visible, because the promoted type is what picks the rendering — `\"\" + +c` prints the code point where `\"\" + c` prints the letter.",
"char c = 'A';\nSystem.out.println(\"\" + +c); // 65\nSystem.out.println(\"\" + c); // A",
),
(
"!",
"Operators",
"!a",
"Logical negation, lowered to `Op::LogNot`.",
"if (!done) { System.out.println(\"still going\"); }",
),
(
"==",
"Operators",
"a == b",
"Equality. Numbers and booleans compare by value and heap objects by handle identity — but two equal *strings* also compare equal, because javars models a `String` as a value rather than a reference. That is the one place `==` diverges: `\"hi\" == \"h\" + \"i\"` is `true` here and `false` in Java.",
"System.out.println(\"hi\" == \"h\" + \"i\"); // true (Java prints false)",
),
(
"!=",
"Operators",
"a != b",
"Inequality — the exact negation of `==`, including its string behaviour.",
"if (n != 0) { System.out.println(100 / n); }",
),
(
"<",
"Operators",
"a < b",
"Less-than. Numeric operands compare numerically; a string operand compares lexicographically by `char` through the numeric hook, which Java would reject at compile time.",
"if (i < 3) { System.out.println(i); }",
),
(
">",
"Operators",
"a > b",
"Greater-than, with the same numeric-or-lexicographic behaviour as `<`.",
"if (score > best) { best = score; }",
),
(
"<=",
"Operators",
"a <= b",
"Less-than-or-equal.",
"for (int i = 1; i <= 10; i++) { }",
),
(
">=",
"Operators",
"a >= b",
"Greater-than-or-equal.",
"if (n >= 0) { System.out.println(\"non-negative\"); }",
),
(
"&&",
"Operators",
"a && b",
"Short-circuiting conjunction: the right operand is not evaluated when the left is false. Lowered to `Op::JumpIfFalseKeep`, so no builtin call and no allocation are involved.",
"if (s != null && s.length() > 0) { System.out.println(s); }",
),
(
"||",
"Operators",
"a || b",
"Short-circuiting disjunction, the mirror of `&&` via `Op::JumpIfTrueKeep`.",
"if (n < 0 || n > 100) { System.out.println(\"out of range\"); }",
),
(
"=",
"Operators",
"name = expr; | a[i] = expr; | obj.f = expr;",
"Assignment, in the three target forms javars lowers separately: a local or global slot, an array element through `JARRAY_SET`, and an instance field through `JFIELD_SET`. Assignment is a statement, not an expression — `x = y = 0` does not parse.",
"int n = 0;\nn = 5;\narr[0] = n;",
),
(
"+=",
"Operators",
"target += expr;",
"Compound addition, on any of the three assignable targets. When the target is declared `int` the result is narrowed back to 32 bits on store, so `int` overflow wraps exactly as `javac` compiles it. With a `String` target it appends.",
"int i = 5; i += 2; // 7\nString s = \"a\"; s += \"b\"; // \"ab\"",
),
(
"-=",
"Operators",
"target -= expr;",
"Compound subtraction, with the same `int` narrowing on store.",
"int i = 5; i -= 2; // 3",
),
(
"*=",
"Operators",
"target *= expr;",
"Compound multiplication.",
"int i = 5; i *= 2; // 10",
),
(
"/=",
"Operators",
"target /= expr;",
"Compound division, following the same integral-versus-floating split as `/`.",
"int i = 10; i /= 2; // 5",
),
(
"%=",
"Operators",
"target %= expr;",
"Compound remainder.",
"int i = 10; i %= 4; // 2",
),
(
"++",
"Operators",
"name++; | a[i]++; | obj.f++;",
"Post-increment. JLS 15.14.2 defines it as `+= 1` with the implicit narrowing cast a compound assignment carries, so `byte b = 127; b++` is -128 and an `int` wraps at 32 bits. In value position it evaluates to the value the target *held*, with the update applied after; the prefix form `++i` updates first and evaluates to the new value. Any lvalue works — a local, an array element, an instance field, a `static` — and the array, index, or receiver is evaluated exactly once, so `a[idx()]++` calls `idx()` a single time.",
"for (int i = 0; i < 3; i++) { }\nint v = 5; System.out.println(v++ + \",\" + v); // 5,6\nint w = 5; System.out.println(++w + \",\" + w); // 6,6\nint[] a = {1}; System.out.println(a[0]++ + \",\" + a[0]); // 1,2",
),
(
"--",
"Operators",
"name--; | a[i]--; | obj.f--;",
"Post-decrement, with the same value-position rule as `++`: `n--` evaluates to the old value, `--n` to the new one.",
"int n = 3; n--; // 2\nint m = 3; System.out.println(--m); // 2",
),
(
"&",
"Operators",
"a & b",
"Bitwise AND on integral operands (fusevm's native `Op::BitAnd`), and Java's *non-short-circuiting* logical AND on `boolean` operands — where the result must stay a boolean rather than the 0/1 an integer op would leave, so it lowers to `Op::LogAnd` instead. The operand types decide which.",
"System.out.println(5 & 3); // 1\nSystem.out.println(true & false); // false",
),
(
"|",
"Operators",
"a | b",
"Bitwise OR, and the non-short-circuiting logical OR on booleans — the mirror of `&`. Also the separator of a multi-catch's alternative types.",
"System.out.println(5 | 3); // 7\nSystem.out.println(true | false); // true",
),
(
"^",
"Operators",
"a ^ b",
"Bitwise XOR on integers; on two booleans it is exactly \"they differ\", lowered to `Op::NumNe` so the result prints `true`/`false`.",
"System.out.println(5 ^ 3); // 6\nSystem.out.println(true ^ true); // false",
),
(
"~",
"Operators",
"~a",
"Bitwise complement of an integral operand (`Op::BitNot`). Unary numeric promotion widens `byte`/`short`/`char` to `int` and leaves `long` alone.",
"System.out.println(~5); // -6",
),
(
"<<",
"Operators",
"a << n",
"Left shift. Java masks the distance to the width of the **left** operand — 5 bits for `int`, 6 for `long` — so `1 << 33` is `1 << 1`; only that operand is promoted, so `1 << 2L` is still an `int`. The mask is emitted explicitly because fusevm's `Op::Shl` always masks to 6 bits, and an `int` result is narrowed afterwards.",
"System.out.println(1 << 31); // -2147483648\nSystem.out.println(1 << 33); // 2\nSystem.out.println(1L << 40); // 1099511627776",
),
(
">>",
"Operators",
"a >> n",
"Arithmetic (sign-propagating) right shift, with the same width masking as `<<`. Lexed as one token, which is why every generic-argument skipper weighs a closing token by how many `>` it spells — otherwise `List<List<String>>` would not parse.",
"System.out.println(-8 >> 1); // -4",
),
(
">>>",
"Operators",
"a >>> n",
"Logical (zero-fill) right shift. Java zero-fills at the operand's width, which fusevm has no native op for — `Op::Shr` is always arithmetic on 64 bits — so this routes through the `JUSHR` builtin with the width the compiler determined.",
"System.out.println(-8 >>> 1); // 2147483644\nSystem.out.println(-8L >>> 1); // 9223372036854775804",
),
(
"&= |= ^= <<= >>= >>>=",
"Operators",
"target &= expr; | target <<= expr; | target >>>= expr;",
"The bitwise and shift compound assignments, on any of the three assignable targets. Each applies the same rules as its binary form: the shifts mask their distance to the *target's* width and `>>>=` zero-fills at it, and `&=`/`|=`/`^=` stay logical when the operand is a boolean.",
"int v = 1; v <<= 3; v |= 1; v &= 14; v ^= 3;\nSystem.out.println(v); // 11",
),
(
"(type) expr",
"Operators",
"(int) d | (byte) n | (char) code | (Object) x",
"A cast. Java's narrowing primitive conversions are real value changes and route through the `JCAST` builtin: floating to integral *saturates* (`(int) 1e18` is `Integer.MAX_VALUE`) and truncates toward zero, and the integral narrowings are two's-complement. A widening or identity cast emits the operand alone, so `(int) i` stays native. A reference cast is a no-op (see `ClassCastException`). `(char) n` produces the one-character string javars models a `char` as.",
"System.out.println((int) 3.99); // 3\nSystem.out.println((byte) 200); // -56\nSystem.out.println((char) 65); // A\nSystem.out.println((double) 7 / 2); // 3.5",
),
(
"?:",
"Operators",
"cond ? a : b",
"The conditional expression. Exactly one arm is evaluated; the untaken arm's code is jumped over, so a side effect in it never runs.",
"String label = n > 4 ? \"big\" : \"small\";",
),
(
"->",
"Operators",
"(params) -> expr | (params) -> { … } | p -> expr",
"The lambda arrow, and the arrow form of `switch`. A lambda becomes a heap closure that snapshots every enclosing local by value at the point the literal runs, which is observationally exact because Java only permits capture of effectively-final locals.",
"Function<Object,Object> up = s -> s + \"!\";\nSystem.out.println(up.apply(\"hi\")); // hi!",
),
(
"::",
"Operators",
"Type::member | value::method | this::method",
"The method-reference separator. Every form is desugared in the compiler into an equivalent lambda with synthesized parameter names, so a method reference and the lambda it stands for share one code path.",
"Function<Object,Object> up = String::toUpperCase;",
),
(
"[]",
"Operators",
"array[index]",
"Array subscript, through `JARRAY_GET` for a read and `JARRAY_SET` for a write. Both are bounds-checked; an out-of-range index raises `ArrayIndexOutOfBoundsException` carrying Java's `Index N out of bounds for length M` message, and a null array raises a NullPointerException.",
"int[] a = {1, 2, 3};\nSystem.out.println(a[1]); // 2",
),
(
".",
"Operators",
"recv.field | recv.method(args) | Class.staticMember",
"Member access. A field read routes through `JFIELD_GET` (which also serves an array's `.length`), an instance call through the receiver's dispatch chain, and a static member through the owning class's chunk global. A `null` receiver raises a NullPointerException naming the operation.",
"System.out.println(p.x);\nSystem.out.println(arr.length);",
),
(
"()",
"Operators",
"name(args) | recv.name(args) | Class.name(args)",
"Invocation. A bare name resolves to a user `static` method (choosing the overload with the lowest assignment cost) or, in a program carrying an inline `rust { … }` block, to an FFI export dispatched by name. Every call site in a program that uses exceptions also carries a pending-exception check.",
"System.out.println(Helper.twice(3));",
),
// ── Console IO: the print builtins in `host.rs` ──
(
"System",
"Console IO",
"System.out | System.err | System.in | System.exit(int) | System.arraycopy(src, sp, dst, dp, n)",
"The `System` class: the two output streams, the input stream `System.in` that a `Scanner` or an `InputStreamReader` wraps, and the statics `exit`, `arraycopy`, `currentTimeMillis`, `nanoTime` and `lineSeparator`. `exit(n)` stops the program where it stands — no `finally` runs — and the process reports `n` modulo 256. `arraycopy` makes Java's checks in Java's order (null, non-array, element-type mismatch, then the index checks) with the JDK's messages, and copies an overlapping range of one array as if through a temporary.",
"int[] a = {1, 2, 3}, b = new int[3];\nSystem.arraycopy(a, 0, b, 1, 2); // b is [0, 1, 2]",
),
(
"Scanner",
"Console IO",
"new Scanner(System.in) | new Scanner(String text)",
"`java.util.Scanner` over stdin or a string. Tokens are delimited by Java whitespace: `next`, `nextInt`/`nextLong`/`nextShort`/`nextByte`, `nextDouble`/`nextFloat`, `nextBoolean`, and the matching `hasNext*` skip delimiters and read one token; `nextLine`/`hasNextLine` answer the rest of the current line (empty right after a `nextInt`). A token that is not the requested type throws `InputMismatchException` and stays unread (an out-of-range integer's message is `For input string: \"…\"`); the root locale's grouping separator is accepted (`1,234`). Exhausted input is `NoSuchElementException` (`No line found` from `nextLine`), and a closed scanner answers `IllegalStateException: Scanner closed`. Every reader over `System.in` shares one stream, filled a line at a time, and stdout is flushed before a read blocks, so a prompt shows before its answer is typed.",
"Scanner sc = new Scanner(System.in);\nint n = sc.nextInt();\nString rest = sc.nextLine();",
),
(
"BufferedReader",
"Console IO",
"new BufferedReader(new InputStreamReader(System.in)) | new BufferedReader(new StringReader(text))",
"`java.io.BufferedReader` over stdin or a `StringReader`. `readLine` answers each line without its terminator (`\\n`, `\\r\\n`, or `\\r`) and `null` at the end of input; `read` answers one character or -1; `lines()` is a stream of the remaining lines; `ready` and `skip` are supported. After `close` every read throws `IOException: Stream closed`.",
"BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\nString line;\nwhile ((line = br.readLine()) != null) System.out.println(line.trim());",
),
(
"StringTokenizer",
"Console IO",
"new StringTokenizer(String s [, String delims [, boolean returnDelims]])",
"`java.util.StringTokenizer`: the tokens of `s` split on any of the delimiter characters (default `\" \\t\\n\\r\\f\"`), with the delimiters themselves as tokens when `returnDelims` is true. `hasMoreTokens`/`hasMoreElements`, `nextToken`/`nextElement` (`NoSuchElementException` when none remain) and `countTokens` are supported.",
"StringTokenizer st = new StringTokenizer(\"3 4\");\nint a = Integer.parseInt(st.nextToken());",
),
(
"PrintWriter",
"Console IO",
"new PrintWriter(System.out [, boolean autoFlush]) | new PrintWriter(Writer w [, boolean autoFlush])",
"`java.io.PrintWriter`: `print`/`println` of every type (by its static type, so a `char` prints as a character and a `float` at 32 bits), `printf`/`format`, `write`, `append`, `flush`, `close` and `checkError`. Over an `OutputStream` it buffers through a `BufferedWriter` and an `OutputStreamWriter`, as the JDK constructor does: text reaches the console at `flush()`, `close()`, an autoflush (`println`/`printf`/`format` when `autoFlush` is set), or a buffer overflow, and what is still buffered when the program ends is lost. A closed `PrintWriter` drops writes and reports it through `checkError()`.",
"PrintWriter out = new PrintWriter(System.out);\nout.println(42);\nout.flush();",
),
(
"BufferedWriter",
"Console IO",
"new BufferedWriter(Writer w) | new OutputStreamWriter(System.out) | new StringWriter()",
"The character writers. A `BufferedWriter` passes its 8192 characters on when it fills and adds `newLine()`; an `OutputStreamWriter` writes its 8192 bytes when the next character no longer fits; a `StringWriter` keeps everything and its `toString()` is the text. `write(int)` writes one character, `write(s, off, len)` a range, and `append` returns the writer. After `close`, a write or flush is `IOException: Stream closed`.",
"BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));\nbw.write(\"hi\");\nbw.newLine();\nbw.flush();",
),
(
"PrintStream",
"Console IO",
"new PrintStream(OutputStream out [, boolean autoFlush]) | new BufferedOutputStream(OutputStream out)",
"The byte streams. A `PrintStream` writes through to the stream it wraps (`System.out` is one) and, with `autoFlush`, flushes on every newline; a `BufferedOutputStream` holds 8192 bytes, flushing them before a write that would overflow. `write(int)` writes the low byte.",
"PrintStream ps = new PrintStream(new BufferedOutputStream(System.out));\nps.println(\"x\");\nps.flush();",
),
(
"System.out",
"Console IO",
"System.out",
"The standard output stream, a `java.io.PrintStream`. As the receiver of `print`/`println`/`printf`/`flush` it lowers straight to the print builtins; named as a value (`PrintStream o = System.out`, `new PrintWriter(System.out)`) it is one shared object with `write`, `append`, `checkError` and `close`. Closing it — directly, or by closing a writer built over it — drops every later write, as in the JDK.",
"System.out.print(\"x\");",
),
(
"System.err",
"Console IO",
"System.err",
"The standard error stream, in every position `System.out` takes and lowered to the stderr pair of print builtins.",
"System.err.println(\"oops\");",
),
(
"System.out.println",
"Console IO",
"void System.out.println([Object x])",
"Prints one argument in Java's `String.valueOf` form followed by a newline, then returns nothing. The Java formatting is the point of the builtin: `true` prints as `true` (not `1`), a whole double as `3.0` (not `3`), and a null reference as `null`. Called with no argument it prints just the newline.",
"System.out.println(\"hello\");\nSystem.out.println();",
),
(
"System.out.print",
"Console IO",
"void System.out.print([Object x])",
"As `println`, but with no trailing newline.",
"System.out.print(\"no newline\");",
),
(
"System.err.println",
"Console IO",
"void System.err.println([Object x])",
"As `System.out.println`, writing to stderr. stdout and stderr are locked and written independently, so redirecting one does not reorder the other.",
"System.err.println(\"to stderr\");",
),
(
"System.err.print",
"Console IO",
"void System.err.print([Object x])",
"As `System.err.println`, with no trailing newline.",
"System.err.print(\"partial\");",
),
// ── String Methods: the `(method, arity)` arms of `host.rs` `string_method` ──
(
"length",
"String Methods",
"int length()",
"The number of UTF-16 code units in the string, as in Java: a character above the BMP counts two, an unpaired surrogate one.",
"System.out.println(\"Hello\".length()); // 5",
),
(
"isEmpty",
"String Methods",
"boolean isEmpty()",
"True when the string has no characters.",
"System.out.println(\"\".isEmpty()); // true",
),
(
"charAt",
"String Methods",
"char charAt(int index)",
"The character at a zero-based scalar index, returned as a one-character string (javars's `char` model). An out-of-range index raises `StringIndexOutOfBoundsException` with Java's exact `Index N out of bounds for length M` message.",
"System.out.println(\"Hello\".charAt(1)); // e",
),
(
"getBytes",
"String Methods",
"byte[] getBytes() | byte[] getBytes(String charsetName) | byte[] getBytes(Charset cs)",
"The string encoded as Java's signed bytes: UTF-8 by default (the JDK 18+ default charset), or `UTF-8`, `ISO-8859-1` or `US-ASCII` by name or by a `StandardCharsets` constant, where a character the charset cannot hold becomes `?`. Any other name is `UnsupportedEncodingException`. `new String(bytes [, offset, length] [, charset])` decodes them back, malformed input becoming U+FFFD.",
"byte[] b = \"hi\".getBytes();\nSystem.out.println(b[0] + \" \" + new String(b)); // 104 hi",
),
(
"substring",
"String Methods",
"String substring(int beginIndex)",
"The suffix beginning at `beginIndex`, on scalar indices.",
"System.out.println(\"Hello\".substring(1)); // ello",
),
(
"substring",
"String Methods",
"String substring(int beginIndex, int endIndex)",
"The half-open range `[beginIndex, endIndex)`, with Java's bounds rule `0 <= begin <= end <= length`. A violation raises `StringIndexOutOfBoundsException` carrying Java's `Range [b, e) out of bounds for length n` message.",
"System.out.println(\"Hello\".substring(1, 3)); // el",
),
(
"indexOf",
"String Methods",
"int indexOf(String str)",
"The scalar index of the first occurrence of `str`, or `-1`. The result is converted from the byte offset the search returns, so it is a character index and not a UTF-8 offset.",
"System.out.println(\"Hello\".indexOf(\"ll\")); // 2",
),
(
"contains",
"String Methods",
"boolean contains(CharSequence s)",
"True when the string contains `s` as a substring.",
"System.out.println(\"Hello\".contains(\"ell\")); // true",
),
(
"equals",
"String Methods",
"boolean equals(Object other)",
"Value equality on the character sequence. Note that javars's `==` already compares strings by value, so `equals` and `==` agree here where Java's would not.",
"System.out.println(\"Hello\".equals(\"Hello\")); // true",
),
(
"equalsIgnoreCase",
"String Methods",
"boolean equalsIgnoreCase(String other)",
"Value equality after lowercasing both sides with Unicode case folding.",
"System.out.println(\"Hello\".equalsIgnoreCase(\"HELLO\")); // true",
),
(
"compareTo",
"String Methods",
"int compareTo(String other)",
"Java's specified ordering value, not merely its sign: the difference of the first differing character, or the length difference when one string is a prefix of the other. That exactness is why a plain lexicographic comparison cannot stand in for it.",
"System.out.println(\"Hello\".compareTo(\"Hellp\")); // -1",
),
(
"compareToIgnoreCase",
"String Methods",
"int compareToIgnoreCase(String other)",
"As `compareTo`, comparing the case-folded characters.",
"System.out.println(\"Hello\".compareToIgnoreCase(\"hello\")); // 0",
),
(
"toUpperCase",
"String Methods",
"String toUpperCase()",
"The string uppercased with Unicode case mapping (locale-independent).",
"System.out.println(\"Hello\".toUpperCase()); // HELLO",
),
(
"toLowerCase",
"String Methods",
"String toLowerCase()",
"The string lowercased with Unicode case mapping.",
"System.out.println(\"Hello\".toLowerCase()); // hello",
),
(
"trim",
"String Methods",
"String trim()",
"Removes leading and trailing characters whose code point is at or below `U+0020` — Java's `trim()` rule, which is deliberately not the same as `strip()`'s `Character.isWhitespace` test (that one keeps the non-breaking spaces `U+00A0`/`U+2007`/`U+202F` and removes the wider Unicode separators).",
"System.out.println(\" x \".trim() + \"|\"); // x|",
),
(
"startsWith",
"String Methods",
"boolean startsWith(String prefix)",
"True when the string begins with `prefix`.",
"System.out.println(\"Hello\".startsWith(\"He\")); // true",
),
(
"startsWith",
"String Methods",
"boolean startsWith(String prefix, int offset)",
"True when the string begins with `prefix` at `offset`. An offset outside the string answers `false` rather than throwing.",
"System.out.println(\"Hello\".startsWith(\"ll\", 2)); // true",
),
(
"endsWith",
"String Methods",
"boolean endsWith(String suffix)",
"True when the string ends with `suffix`.",
"System.out.println(\"Hello\".endsWith(\"lo\")); // true",
),
(
"concat",
"String Methods",
"String concat(String str)",
"The receiver followed by `str`. Equivalent to `+` here, since javars's `+` already concatenates through the same value-to-string rules.",
"System.out.println(\"Hello\".concat(\"!\")); // Hello!",
),
(
"replace",
"String Methods",
"String replace(CharSequence target, CharSequence replacement)",
"Every occurrence of `target` replaced by `replacement`. This is the literal two-argument overload; there is no regex `replaceAll`.",
"System.out.println(\"Hello\".replace(\"l\", \"L\")); // HeLLo",
),
(
"repeat",
"String Methods",
"String repeat(int count)",
"The string repeated `count` times. A negative count raises `IllegalArgumentException` with Java's `count is negative: n` message.",
"System.out.println(\"ab\".repeat(3)); // ababab",
),
(
"chars",
"String Methods",
"IntStream chars() | IntStream codePoints()",
"The characters as a stream of their code points. `chars()` yields UTF-16 code units, so the two differ only above the BMP, where `chars()` yields a surrogate pair's two halves and `codePoints()` the one code point.",
"System.out.println(\"abc\".chars().sum()); // 294",
),
(
"lines",
"String Methods",
"Stream<String> lines()",
"The lines, split on terminators rather than separators: a trailing newline ends the last line instead of starting an empty one, so `\"a\\\\n\"` is one line and `\"\"` is none. All of `\\\\n`, `\\\\r\\\\n` and a lone `\\\\r` terminate.",
"System.out.println(\"a\\\\nb\\\\n\".lines().count()); // 2",
),
// ── Static Library: the `(class, method, arity)` arms of `static_method` ──
(
"AtomicInteger",
"Static Library",
"new AtomicInteger([int]) | new AtomicLong([long]) | new AtomicBoolean([boolean])",
"The `java.util.concurrent.atomic` cells, the counters a lambda body can update. `get`/`set`, `incrementAndGet`/`getAndIncrement` and the decrements, `addAndGet`/`getAndAdd`, `getAndSet`, `compareAndSet`, `updateAndGet`/`getAndUpdate`, `accumulateAndGet`/`getAndAccumulate`; an `AtomicInteger` wraps at 32 bits. javars runs one thread, so each is the plain read-modify-write it names.",
"AtomicInteger n = new AtomicInteger();\nList.of(1, 2).forEach(x -> n.addAndGet(x));\nSystem.out.println(n); // 3",
),
(
"List.copyOf",
"Collection Statics",
"List.copyOf(c) | Set.copyOf(c) | Map.copyOf(m)",
"Immutable copies that refuse a `null` element, key or value; `Set.copyOf` drops repeats where `Set.of` refuses them.",
"System.out.println(List.copyOf(new ArrayList<>(List.of(1, 2)))); // [1, 2]",
),
(
"Collections.nCopies",
"Collection Statics",
"Collections.nCopies(n, o) | emptySortedSet() | emptyNavigableSet()",
"`nCopies` is an immutable list of `n` references to `o` (`IllegalArgumentException: List length = n` for a negative `n`); `emptySortedSet`/`emptyNavigableSet` are the immutable empty sorted set, whose `first()` is `NoSuchElementException`.",
"System.out.println(String.join(\"\", Collections.nCopies(3, \"ab\"))); // ababab",
),
(
"Collections.enumeration",
"Collection Statics",
"Collections.enumeration(c) | list(e) | emptyIterator() | emptyListIterator() | emptyEnumeration()",
"`enumeration(c)` walks `c` through its iterator (`hasMoreElements`/`nextElement`/`asIterator`), so a change to `c` behind it is `ConcurrentModificationException`; `list(e)` drains what an enumeration has left into an `ArrayList`. The empty iterators answer `hasNext()` false, `next()` `NoSuchElementException` and `remove()` `IllegalStateException`.",
"System.out.println(Collections.list(Collections.enumeration(List.of(1, 2)))); // [1, 2]",
),
(
"Collections.singleton",
"Collection Statics",
"Collections.singleton(o) | singletonMap(k, v) | emptySet() | emptyMap()",
"The immutable one- and zero-element sets and maps; unlike `Set.of`/`Map.of` they accept `null`.",
"System.out.println(Collections.singletonMap(\"k\", 1)); // {k=1}",
),
(
"StringJoiner",
"Static Library",
"new StringJoiner(delimiter) | new StringJoiner(delimiter, prefix, suffix)",
"`java.util.StringJoiner`: `add` appends `String.valueOf` of its argument, `toString`/`length` give prefix + elements joined by the delimiter + suffix, `setEmptyValue` replaces that while nothing has been added, and `merge(other)` adds the other joiner's elements as one element joined by its own delimiter (nothing when it has none). A `null` delimiter, prefix, suffix or empty value is `NullPointerException` with the JDK's message.",
"StringJoiner j = new StringJoiner(\", \", \"[\", \"]\");\\nj.add(\"a\").add(\"b\");\\nSystem.out.println(j); // [a, b]",
),
(
"BitSet",
"Static Library",
"new BitSet([int nbits])",
"`java.util.BitSet`, ported from the JDK: `set`/`clear`/`flip`/`get` by index or `[from, to)` range, `cardinality`, `length`, `size` (the JDK's doubling capacity), `isEmpty`, `nextSetBit`/`nextClearBit`/`previousSetBit`/`previousClearBit`, `and`/`or`/`xor`/`andNot`/`intersects`, `stream()`, `clone`, `equals`/`hashCode`, and the `{1, 3, 5}` rendering, with the JDK's index messages (`bitIndex < 0: -1`).",
"BitSet b = new BitSet();\nb.set(1, 4);\nSystem.out.println(b); // {1, 2, 3}",
),
(
"BigInteger",
"Static Library",
"new BigInteger(String [, int radix]) | BigInteger.valueOf(long) | BigInteger.ZERO/ONE/TWO/TEN",
"`java.math.BigInteger`: arbitrary-precision integers. `add`/`subtract`/`multiply`, truncating `divide`/`remainder` and flooring `mod`, `divideAndRemainder`, `pow`, `modPow`, `modInverse`, `gcd`, `sqrt`, `negate`/`abs`/`signum`, `min`/`max`, two's-complement `and`/`or`/`xor`/`not`/`andNot`/`shiftLeft`/`shiftRight`/`testBit`/`setBit`/`clearBit`/`flipBit`, `bitLength`/`bitCount`/`getLowestSetBit`, `compareTo`/`equals`/`hashCode`, `toString(radix)`, the narrowing `intValue`/`longValue` and the `*Exact` forms, `toByteArray`, `isProbablePrime`/`nextProbablePrime`. Exception messages are the JDK's (`BigInteger divide by zero`, `Negative exponent`). `%d`/`%x`/`%o` format it from its digits.",
"BigInteger f = BigInteger.ONE;\nfor (int i = 2; i <= 25; i++) f = f.multiply(BigInteger.valueOf(i));\nSystem.out.println(f); // 15511210043330985984000000",
),
(
"BigDecimal",
"Static Library",
"new BigDecimal(String | int | long | double | BigInteger [, MathContext]) | BigDecimal.valueOf(long [, int scale] | double) | BigDecimal.ZERO/ONE/TWO/TEN",
"`java.math.BigDecimal`: an unscaled `BigInteger` and a scale. `add`/`subtract`/`multiply`, `divide(x)` (exact, or `Non-terminating decimal expansion`), `divide(x, scale, mode)`, `divide(x, mode)`, `divide(x, mc)` with the JDK's preferred-scale stripping, `remainder`, `divideToIntegralValue`, `pow`, `sqrt(mc)`, `setScale`, `round(mc)`, `stripTrailingZeros`, `movePointLeft`/`movePointRight`, `scaleByPowerOfTen`, `precision`/`scale`/`unscaledValue`, `compareTo` (numeric) against `equals`/`hashCode` (value and scale), `toString` (scientific past six leading zeros), `toPlainString`, the narrowing and `*Exact` conversions. `%f` and `%e` format it from its digits, rounding HALF_UP, never through a `double`.",
"BigDecimal p = new BigDecimal(\"19.99\").multiply(BigDecimal.valueOf(3));\nSystem.out.println(p.setScale(1, RoundingMode.HALF_UP)); // 60.0",
),
(
"MathContext",
"Static Library",
"new MathContext(int precision [, RoundingMode]) | MathContext.DECIMAL32/DECIMAL64/DECIMAL128/UNLIMITED",
"`java.math.MathContext`: a digit budget and a rounding mode, accepted by `BigDecimal.divide`/`round`/`sqrt`/`add`/`subtract`/`multiply`. `getPrecision`, `getRoundingMode`, and the `precision=7 roundingMode=HALF_EVEN` rendering.",
"MathContext mc = new MathContext(5, RoundingMode.DOWN);\nSystem.out.println(new BigDecimal(\"1.23456789\").round(mc)); // 1.2345",
),
(
"RoundingMode",
"Static Library",
"RoundingMode.UP | DOWN | CEILING | FLOOR | HALF_UP | HALF_DOWN | HALF_EVEN | UNNECESSARY",
"`java.math.RoundingMode`: one canonical object per constant, so `==` is identity; `values()`, `valueOf(String)`, `name()`, `ordinal()`, `compareTo`. `UNNECESSARY` raises `ArithmeticException: Rounding necessary` when any digit would be dropped.",
"System.out.println(RoundingMode.valueOf(\"HALF_EVEN\").ordinal()); // 6",
),
(
"Collections.addAll",
"Collection Statics",
"boolean Collections.addAll(Collection<T> c, T... elements)",
"Adds each element through the collection's own `add` and answers whether any call changed it.",
"Collections.addAll(xs, 1, 2, 3);",
),
(
"Pattern",
"Static Library",
"Pattern.compile(String regex [, int flags]) | Pattern.matches(regex, input) | Pattern.quote(s)",
"A compiled `java.util.regex` pattern on the same translation `String.matches` uses. `matcher(input)` starts a `Matcher`; `pattern()`/`toString()` answer the source, `flags()` the flags, `split`/`splitAsStream` split as `String.split` does. `CASE_INSENSITIVE`, `DOTALL` and `LITERAL` are modeled; the other flags are refused by name. A malformed pattern raises `PatternSyntaxException` at `compile`.",
"Pattern p = Pattern.compile(\"(\\\\w+)@(\\\\w+)\");",
),
(
"Matcher",
"Static Library",
"boolean find() | find(int) | matches() | lookingAt() | String group([int | String]) | int start([g]) | int end([g])",
"The JDK's matcher state over one input: `find` resumes after the last match (one character on after an empty one), `matches`/`lookingAt` anchor at the whole input or its start, `group` answers `null` for a group that did not take part, and indices are UTF-16. `groupCount`, `reset([input])`, `replaceAll`/`replaceFirst`, `appendReplacement`/`appendTail`, `results()` and `toMatchResult()` are supported; with no current match the accessors throw `IllegalStateException: No match found`.",
"Matcher m = p.matcher(\"bob@site\");\nwhile (m.find()) System.out.println(m.group(2));",
),
(
"StrictMath",
"Static Library",
"StrictMath.sin(double) | StrictMath.cos(double) | every other `Math` member",
"`java.lang.StrictMath`. `sin` and `cos` are the JDK's fdlibm (`java.lang.FdLibm`), bit for bit; every other member is read as the `Math` member of the same name, which javars already answers from fdlibm or an exact IEEE operation, so the two classes agree wherever the JDK's do.",
"System.out.println(StrictMath.sin(1.0) + \" \" + StrictMath.cos(2.0));",
),
(
"Math.sin",
"Static Library",
"double Math.sin(double a)",
"The sine. Ported from HotSpot's aarch64 `dsin` intrinsic, which every `Math.sin` call on that JVM runs, so the result is its to the last bit — and differs from `StrictMath.sin` (fdlibm) in the last place on some arguments.",
"System.out.println(Math.sin(Math.PI / 6));",
),
(
"Math.cos",
"Static Library",
"double Math.cos(double a)",
"The cosine. Ported from HotSpot's aarch64 `dcos` intrinsic, which every `Math.cos` call on that JVM runs, so the result is its to the last bit — and differs from `StrictMath.cos` (fdlibm) in the last place on some arguments.",
"System.out.println(Math.cos(1.0));",
),
(
"Math.tan",
"Static Library",
"double Math.tan(double a)",
"The tangent. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.tan(0.5));",
),
(
"Math.asin",
"Static Library",
"double Math.asin(double a)",
"The arc sine, in [-pi/2, pi/2]; NaN outside [-1, 1]. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.asin(0.5));",
),
(
"Math.acos",
"Static Library",
"double Math.acos(double a)",
"The arc cosine, in [0, pi]; NaN outside [-1, 1]. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.acos(0.5));",
),
(
"Math.atan",
"Static Library",
"double Math.atan(double a)",
"The arc tangent, in [-pi/2, pi/2]. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.atan(0.5));",
),
(
"Math.atan2",
"Static Library",
"double Math.atan2(double y, double x)",
"The angle of the point (x, y), in [-pi, pi], with the JDK's signed-zero and infinity cases. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.atan2(3.0, 4.0));",
),
(
"Math.exp",
"Static Library",
"double Math.exp(double a)",
"e raised to a. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.exp(0.5));",
),
(
"Math.log",
"Static Library",
"double Math.log(double a)",
"The natural logarithm; -Infinity at zero, NaN below it. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.log(0.5));",
),
(
"Math.log10",
"Static Library",
"double Math.log10(double a)",
"The base-10 logarithm, exact at powers of ten. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.log10(0.5));",
),
(
"Math.log1p",
"Static Library",
"double Math.log1p(double x)",
"ln(1 + x), accurate for x near zero. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.log1p(0.5));",
),
(
"Math.expm1",
"Static Library",
"double Math.expm1(double x)",
"e^x - 1, accurate for x near zero. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.expm1(0.5));",
),
(
"Math.cbrt",
"Static Library",
"double Math.cbrt(double a)",
"The cube root, keeping the sign. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.cbrt(0.5));",
),
(
"Math.hypot",
"Static Library",
"double Math.hypot(double x, double y)",
"sqrt(x^2 + y^2) without intermediate overflow or underflow. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.hypot(3.0, 4.0));",
),
(
"Math.sinh",
"Static Library",
"double Math.sinh(double x)",
"The hyperbolic sine. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.sinh(0.5));",
),
(
"Math.cosh",
"Static Library",
"double Math.cosh(double x)",
"The hyperbolic cosine. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.cosh(0.5));",
),
(
"Math.tanh",
"Static Library",
"double Math.tanh(double x)",
"The hyperbolic tangent. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.tanh(0.5));",
),
(
"Math.asinh",
"Static Library",
"double Math.asinh(double x)",
"The inverse hyperbolic sine. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.asinh(0.5));",
),
(
"Math.acosh",
"Static Library",
"double Math.acosh(double x)",
"The inverse hyperbolic cosine; NaN below 1. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.acosh(0.5));",
),
(
"Math.atanh",
"Static Library",
"double Math.atanh(double x)",
"The inverse hyperbolic tangent; NaN outside [-1, 1]. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.atanh(0.5));",
),
(
"Math.IEEEremainder",
"Static Library",
"double Math.IEEEremainder(double f1, double f2)",
"f1 - f2 * n with n the integer nearest f1 / f2 (ties to even). Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.IEEEremainder(3.0, 4.0));",
),
(
"Math.scalb",
"Static Library",
"double Math.scalb(double d, int scaleFactor)",
"d * 2^scaleFactor, rounded once. Ported from the JDK's fdlibm (`java.lang.FdLibm`), so the result is `StrictMath`'s to the last bit.",
"System.out.println(Math.scalb(1.5, 3));",
),
(
"Random",
"Static Library",
"new Random() | new Random(long seed)",
"`java.util.Random`, the JDK's 48-bit linear congruential generator, so a seeded generator draws exactly the JDK's sequence: `nextInt()`, `nextInt(bound)`, `nextInt(origin, bound)`, `nextLong()` and its bounded forms, `nextDouble()` and its bounded forms, `nextFloat`, `nextBoolean`, `nextGaussian` (fdlibm's `log`, as `StrictMath` computes it), `nextBytes` and `setSeed`. The sized stream factories `ints(n)`, `ints(n, origin, bound)` and the `longs`/`doubles` pairs draw the same sequence the matching `next…` calls would; the unsized (infinite) forms are not modeled. A bad bound is the JDK's `IllegalArgumentException` (`bound must be positive`, `bound must be greater than origin`). An unseeded generator is seeded from the clock, as the JDK's is.",
"Random r = new Random(42);\\nSystem.out.println(r.nextInt(100)); // 30",
),
(
"Locale",
"Static Library",
"Locale.ROOT | Locale.US | Locale.UK | Locale.ENGLISH | Locale.CANADA",
"The locales whose number formatting is the root locale's, which is the only formatting javars does. As the leading argument of `String.format`, `printf`/`format` or `toUpperCase`/`toLowerCase` the call is the one without it; `toString()` is the JDK's (`en_US`, the empty string for `ROOT`). The other locales are not modeled.",
"System.out.println(String.format(Locale.US, \"%,.2f\", 1234.5)); // 1,234.50",
),
(
"System.getProperty",
"Static Library",
"String System.getProperty(String key) | (String key, String def) | String System.getenv(String name)",
"`line.separator`, `file.separator` and `path.separator` answer the platform's values; any other key in a namespace that describes the JVM (`java.`, `os.`, `user.`, …) is refused, since javars is not one; any other key was never set, so it is `null` or the default. `getenv` reads the process environment.",
"System.out.println(System.getProperty(\"app.mode\", \"dev\")); // dev",
),
(
"Math.random",
"Static Library",
"double Math.random()",
"A uniform `double` in `[0, 1)`, from one unseeded `Random` created on first use.",
"double d = Math.random();",
),
(
"Math.abs",
"Static Library",
"int Math.abs(int a) | double Math.abs(double a)",
"Absolute value, keeping the operand's kind: an integral argument returns an integer, anything else returns a double. The result type is deliberately not modeled statically, because claiming either would mis-type the other overload.",
"System.out.println(Math.abs(-3) + \" \" + Math.abs(-3.5)); // 3 3.5",
),
(
"Math.max",
"Static Library",
"int Math.max(int a, int b) | double Math.max(double a, double b)",
"The larger of two values; integral when both operands are integral, double otherwise. A `NaN` operand propagates (unlike C's `fmax` and Rust's `f64::max`, which return the other operand), and `max(-0.0, 0.0)` is `0.0`.",
"System.out.println(Math.max(1, 2)); // 2",
),
(
"Math.min",
"Static Library",
"int Math.min(int a, int b) | double Math.min(double a, double b)",
"The smaller of two values, with the same integral-versus-double rule as `max` — and the same `NaN` propagation, which `f64::min` does not do.",
"System.out.println(Math.min(1.5, 2)); // 1.5",
),
(
"Math.pow",
"Static Library",
"double Math.pow(double a, double b)",
"`a` raised to the power `b`, always as a double. Java departs from IEEE `pow` twice: a `NaN` exponent gives `NaN` even for a base of 1, and `|a| == 1` with an infinite exponent gives `NaN`. A zero exponent still gives `1.0` for every base.",
"System.out.println(Math.pow(2, 10)); // 1024.0",
),
(
"Math.sqrt",
"Static Library",
"double Math.sqrt(double a)",
"Square root, always as a double. A negative argument gives NaN rather than faulting, as in Java.",
"System.out.println(Math.sqrt(9)); // 3.0",
),
(
"Math.floor",
"Static Library",
"double Math.floor(double a)",
"The largest double less than or equal to `a` that is a mathematical integer.",
"System.out.println(Math.floor(1.7)); // 1.0",
),
(
"Math.ceil",
"Static Library",
"double Math.ceil(double a)",
"The smallest double greater than or equal to `a` that is a mathematical integer.",
"System.out.println(Math.ceil(1.2)); // 2.0",
),
(
"Math.round",
"Static Library",
"long Math.round(double a) | int Math.round(float a)",
"Java's rounding: ties go toward positive infinity, so `round(-2.5)` is `-2` where Rust's half-away-from-zero `round` gives `-3`. It is *not* `floor(a + 0.5)` either — that was the pre-Java-7 implementation and it answers 1 for `0.49999999999999994`, where Java answers 0. A `float` argument selects the overload returning `int`, which saturates at `Integer.MAX_VALUE`.",
"System.out.println(Math.round(-2.5)); // -2",
),
(
"Math.rint",
"Static Library",
"double Math.rint(double a)",
"Rounds to the nearest integral `double`, ties going to the **even** neighbour — the IEEE `roundToIntegralTiesToEven` operation, and therefore not `Math.round`'s ties-toward-positive-infinity: `rint(2.5)` is `2.0` while `round(2.5)` is `3`.",
"System.out.println(Math.rint(2.5) + \" \" + Math.rint(3.5)); // 2.0 4.0",
),
(
"Math.copySign",
"Static Library",
"double Math.copySign(double magnitude, double sign)",
"The magnitude of the first argument with the sign of the second. The sign of a zero counts, so `copySign(3.0, -0.0)` is `-3.0`.",
"System.out.println(Math.copySign(3.0, -0.0)); // -3.0",
),
(
"Math.ulp",
"Static Library",
"double Math.ulp(double d) | float Math.ulp(float f)",
"The distance from `d` to the next representable `double` away from zero — the size of one unit in the last place. `ulp(Double.MAX_VALUE)` is measured downward, because one step further would be infinity. `Math.ulp(float)` measures in `float` units: `Math.ulp(1.0f)` is `1.1920929E-7`.",
"System.out.println(Math.ulp(1.0)); // 2.220446049250313E-16",
),
(
"Math.getExponent",
"Static Library",
"int Math.getExponent(double d) | int Math.getExponent(float f)",
"The unbiased binary exponent of the argument. NaN and the infinities answer one past the largest normal exponent (`1024` for `double`, `128` for `float`) and zero and the subnormals one below the smallest (`-1023`, `-127`).",
"System.out.println(Math.getExponent(8.0) + \" \" + Math.getExponent(0.1f)); // 3 -4",
),
(
"Math.nextUp",
"Static Library",
"double Math.nextUp(double d) | double Math.nextDown(double d)",
"The representable `double` adjacent to `d` toward positive (`nextUp`) or negative (`nextDown`) infinity. Both zeros step to the smallest subnormal of the target's sign. The `float` overloads, chosen by a statically-`float` argument, step to the adjacent `float` and answer one: `Math.nextUp(1.0f)` is `1.0000001`.",
"System.out.println(Math.nextUp(1.0)); // 1.0000000000000002",
),
(
"Math.nextAfter",
"Static Library",
"double Math.nextAfter(double start, double direction)",
"The representable `double` adjacent to `start` in the direction of `direction`, or `direction` itself when the two are equal.",
"System.out.println(Math.nextAfter(1.0, 0.0)); // 0.9999999999999999",
),
(
"Math.fma",
"Static Library",
"double Math.fma(double a, double b, double c)",
"`a * b + c` computed as one fused operation, rounded **once** — so it is not the same number as writing the two operations separately when the exact product needs more than 53 bits.",
"System.out.println(Math.fma(2.0, 3.0, 4.0)); // 10.0",
),
(
"Math.addExact",
"Static Library",
"int Math.addExact(int a, int b) | long Math.addExact(long a, long b) | subtractExact | multiplyExact",
"The arithmetic that raises `ArithmeticException` instead of wrapping. The overload is chosen from the arguments' **static** types and the two disagree exactly where the method is interesting: the `int` one overflows at 2^31 with `integer overflow`, the `long` one at 2^63 with `long overflow`. A call whose argument types javars cannot infer is refused, naming the method.",
"System.out.println(Math.addExact(2000000000L, 2000000000L)); // 4000000000",
),
(
"Math.toIntExact",
"Static Library",
"int Math.toIntExact(long value)",
"`value` narrowed to an `int`, or `ArithmeticException: integer overflow` when it does not fit — the checked counterpart of the `(int)` cast, which wraps silently.",
"System.out.println(Math.toIntExact(5L)); // 5",
),
(
"Math.clamp",
"Static Library",
"int Math.clamp(long v, int min, int max) | long | double | float",
"`v` confined to `[min, max]`. The **bounds** pick the overload, so `clamp(aLong, 1, 10)` answers an `int` and `clamp(aLong, 1L, 10L)` a `long`. `min > max` is `IllegalArgumentException: \"<min> > <max>\"`, a NaN bound is `min is NaN` / `max is NaN`, and a NaN value passes through.",
"System.out.println(Math.clamp(15, 1, 10)); // 10",
),
(
"Integer.parseInt",
"Static Library",
"int Integer.parseInt(String s)",
"Parses a signed decimal integer with `java.lang.Integer`'s exact rules: no surrounding whitespace is tolerated and the value must fit 32 bits. Every failure raises `NumberFormatException` carrying Java's own `For input string: \"…\"` message.",
"System.out.println(Integer.parseInt(\"42\")); // 42",
),
(
"Integer.parseInt",
"Static Library",
"int Integer.parseInt(String s, int radix)",
"As above in the given radix, which must lie between `Character.MIN_RADIX` and `Character.MAX_RADIX`. A bad radix and a bad digit string produce Java's two distinct `NumberFormatException` messages.",
"System.out.println(Integer.parseInt(\"ff\", 16)); // 255",
),
(
"Integer.valueOf",
"Static Library",
"int Integer.valueOf(String s) | int Integer.valueOf(int i)",
"Parses a decimal string with `parseInt`'s rules, or boxes an integral argument. The box has Java's identity: `Integer.valueOf(1000) == Integer.valueOf(1000)` is `false`, as it is outside the JDK's small-value cache. `valueOf(String s, int radix)` parses in the given radix.",
"System.out.println(Integer.valueOf(\"7\")); // 7",
),
(
"Integer.toString",
"Static Library",
"String Integer.toString(int i)",
"The decimal rendering of an integer.",
"System.out.println(Integer.toString(255)); // 255",
),
(
"Integer.toString",
"Static Library",
"String Integer.toString(int i, int radix)",
"The rendering in radix 2 through 36, sign-prefixed for negatives. An out-of-range radix falls back to 10, exactly as Java specifies.",
"System.out.println(Integer.toString(255, 16)); // ff",
),
(
"Long.parseLong",
"Static Library",
"long Long.parseLong(String s)",
"Parses a signed decimal `long`, using the same rules and the same `NumberFormatException` messages as `parseInt` but with the 64-bit width check.",
"System.out.println(Long.parseLong(\"9000000000\")); // 9000000000",
),
(
"Boolean.parseBoolean",
"Static Library",
"boolean Boolean.parseBoolean(String s)",
"True when the string equals `\"true\"` ignoring ASCII case, false for everything else — including `null` and malformed input, which Java also never rejects here.",
"System.out.println(Boolean.parseBoolean(\"TRUE\")); // true",
),
(
"String.valueOf",
"Static Library",
"String String.valueOf(Object x)",
"Renders any value with Java's `println` rules: `true`/`false`, a whole double with its trailing `.0`, `null` for a null reference, and `ClassName@hash` for an instance whose class declares no `toString()`.",
"System.out.println(String.valueOf(3.0)); // 3.0",
),
(
"String.copyValueOf",
"Static Library",
"String String.copyValueOf(char[] data)",
"The characters of `data` as a `String`. The JDK implements it as one call to `String.valueOf(char[])`, and so does javars.",
"System.out.println(String.copyValueOf(new char[]{'a', 'b'})); // ab",
),
(
"StringBuilder",
"Static Library",
"new StringBuilder() | new StringBuilder(int capacity) | new StringBuilder(String s)",
"The mutable character sequence, and `StringBuffer` alongside it (javars runs one thread, so the two differ only in their class name). `append`/`insert`/`delete`/`deleteCharAt`/`replace`/`reverse`/`setCharAt`/`setLength`/`charAt`/`substring`/`indexOf`/`lastIndexOf`/`codePointAt`/`codePointBefore`/`codePointCount`/`length`/`isEmpty`/`capacity`/`compareTo`/`toString` are implemented, the mutators answering the receiver so a chain keeps building. A builder is a reference: passing one to a method or storing it in a collection denotes the one object, `equals` stays `Object`'s identity comparison, and `toString` — and therefore `println(sb)`, `\"\" + sb` and `%s` — is the contents. `capacity()` reproduces the JDK's growth curve (16 to start, then `2 * old + 2`), because it is observable.",
"StringBuilder b = new StringBuilder();\nfor (int i = 0; i < 3; i++) { b.append(i).append(','); }\nSystem.out.println(b); // 0,1,2,",
),
(
"String.format",
"Static Library",
"String String.format(String fmt, Object... args)",
"printf-style formatting — a faithful subset of `java.util.Formatter` covering the conversions `d s S f e E g G a A b B h H x X o c %` and `%n`, all seven flags `-` `#` `+` ` ` `0` `,` `(`, an optional width, an optional `.precision`, explicit argument indexes (`%2$s`), and the relative index `%<s`. `%f` rounds HALF_UP on the double's exact value, as Java does. `System.out.printf` is the same formatter with no trailing newline. An unsupported conversion is reported rather than rendered wrong.",
"System.out.println(String.format(\"%05.2f|%-6s|%+d\", 3.14159, \"ab\", 7)); // 03.14|ab |+7",
),
(
"Arrays.toString",
"Static Library",
"String Arrays.toString(Object[] a)",
"The shallow `[e0, e1, …]` rendering of an array, each element through the same Java value-to-string rules. A null reference renders as `null`; a nested array renders as its handle, since the rendering is shallow.",
"System.out.println(Arrays.toString(new int[]{1, 2, 3})); // [1, 2, 3]",
),
(
"Arrays.sort",
"Static Library",
"void Arrays.sort(T[] a) | (T[] a, Comparator<T> c) | (T[] a, int from, int to) | (T[] a, int from, int to, Comparator<T> c)",
"Sorts the array, or its `[from, to)` range, in place. A primitive array sorts numerically (`-0.0` before `0.0`, NaN last); a reference array with no comparator, or a `null` one, orders by the elements' own `compareTo`; a comparator sorts through the same stable merge sort as `List.sort`. The range is checked as `Arrays.rangeCheck` does: `from > to` is `IllegalArgumentException: fromIndex(3) > toIndex(1)` and an index outside the array is `ArrayIndexOutOfBoundsException: Array index out of range: 9`.",
"int[][] g = {{3, 1}, {2, 2}};\nArrays.sort(g, (x, y) -> x[0] - y[0]);\nSystem.out.println(Arrays.deepToString(g)); // [[2, 2], [3, 1]]",
),
(
"Integer.decode",
"Static Library",
"int Integer.decode(String s)",
"An optional sign, then a `0x`/`0X`/`#` hexadecimal, a leading-`0` octal, or a decimal literal. The sign is read before the radix prefix, so `-0x80000000` is `Integer.MIN_VALUE` and `0x-1` is `NumberFormatException: Sign character in wrong position`.",
"System.out.println(Integer.decode(\"0x1F\") + \" \" + Integer.decode(\"010\")); // 31 8",
),
(
"Long.decode",
"Static Library",
"long Long.decode(String s)",
"`Integer.decode`'s grammar and messages at 64 bits, so `-0x8000000000000000` is `Long.MIN_VALUE`.",
"System.out.println(Long.decode(\"#ff\") + \" \" + Long.decode(\"-010\")); // 255 -8",
),
(
"Arrays.deepHashCode",
"Static Library",
"int Arrays.hashCode(T[] a) | int Arrays.deepHashCode(Object[] a)",
"The `31 * h + e` fold seeded at 1 over the elements' hashes, wrapping at 32 bits; a `null` array is 0. `deepHashCode` folds a nested array by its own `deepHashCode` rather than its identity.",
"System.out.println(Arrays.deepHashCode(new int[][]{{1, 2}, {3}})); // 31809",
),
(
"Arrays.parallelPrefix",
"Static Library",
"void Arrays.parallelPrefix(T[] a, BinaryOperator<T> op) | (T[] a, int from, int to, BinaryOperator<T> op)",
"Replaces each element of the array, or of its `[from, to)` range, with `op` folded over it and every element before it in the range. The range is checked as `Arrays.sort`'s is. javars folds left to right; the JDK's parallel evaluation gives the same answer for the associative operator the method requires.",
"int[] p = {1, 2, 3, 4};\nArrays.parallelPrefix(p, Integer::sum);\nSystem.out.println(Arrays.toString(p)); // [1, 3, 6, 10]",
),
(
"Integer.parseUnsignedInt",
"Static Library",
"int Integer.parseUnsignedInt(String s) | (String s, int radix)",
"A non-negative number up to 2^32 - 1, answered as the `int` with that bit pattern. A leading `-` and a value past the range each raise `NumberFormatException` with the JDK's own message.",
"System.out.println(Integer.parseUnsignedInt(\"4294967295\")); // -1",
),
(
"Integer.divideUnsigned",
"Static Library",
"int Integer.divideUnsigned(int a, int b) | remainderUnsigned | compareUnsigned | toUnsignedLong | toUnsignedString",
"The operands read as unsigned 32-bit values. The `Long` overloads read 64 bits. A zero divisor is `ArithmeticException: / by zero`.",
"System.out.println(Integer.divideUnsigned(-1, 2) + \" \" + Integer.toUnsignedString(-1)); // 2147483647 4294967295",
),
(
"Short.parseShort",
"Static Library",
"short Short.parseShort(String s[, int radix]) | byte Byte.parseByte(String s[, int radix])",
"`Integer.parseInt` at the given radix, then a range check whose failure is `NumberFormatException: Value out of range. Value:\"200\" Radix:10`. `Short`/`Byte` also carry `valueOf`, `compare` (the difference, not a sign), `toUnsignedInt`, `toString` and `hashCode`.",
"System.out.println(Byte.parseByte(\"-12\") + \" \" + Short.parseShort(\"7f\", 16)); // -12 127",
),
(
"Character.isDigit",
"Static Library",
"boolean Character.isDigit(char c) | isLetter | isLetterOrDigit | isAlphabetic | isSpaceChar | isISOControl | isWhitespace | isUpperCase | isLowerCase",
"Unicode general-category predicates, as Java defines them: `isDigit` is DECIMAL_DIGIT_NUMBER in every script (`'٣'` is a digit), `isLetter` excludes the `Other_Alphabetic` marks and letter numbers that `isAlphabetic` includes, `isSpaceChar` counts the no-break spaces that `isWhitespace` does not. A sweep of all 65,536 `char` values is byte-identical to openjdk 27.",
"System.out.println(Character.isDigit('\\u0663') + \" \" + Character.isLetter('\\u0345')); // true false",
),
(
"Character.digit",
"Static Library",
"int Character.digit(char c, int radix) | char Character.forDigit(int digit, int radix)",
"`digit` is the value of a decimal digit of any script, or of an ASCII or fullwidth Latin letter as 10..35, when that value is below `radix`; -1 otherwise and for a radix outside 2..36. `forDigit` is its inverse over lowercase ASCII, and the NUL `char` when the digit or radix is out of range.",
"System.out.println(Character.digit('f', 16) + \" \" + Character.forDigit(11, 16)); // 15 b",
),
(
"Integer.bitCount",
"Static Library",
"int Integer.bitCount(int i) | int Long.bitCount(long i)",
"The number of one-bits in the two's complement representation, read at the declared width — so `Integer.bitCount(-1)` is 32 and `Long.bitCount(-1L)` is 64.",
"System.out.println(Integer.bitCount(255) + \" \" + Long.bitCount(-1L)); // 8 64",
),
(
"Integer.reverse",
"Static Library",
"int Integer.reverse(int i) | int Integer.reverseBytes(int i)",
"`reverse` reverses the bit order, `reverseBytes` the byte order, each at the declared width. `Integer.reverse(1)` is `Integer.MIN_VALUE`; the `Long` overloads answer at 64 bits.",
"System.out.println(Integer.reverse(1)); // -2147483648",
),
(
"Short.reverseBytes",
"Static Library",
"short Short.reverseBytes(short i) | char Character.reverseBytes(char ch)",
"The two bytes swapped: a signed `short` from `Short`, an unsigned `char` from `Character`.",
"System.out.println(Short.reverseBytes((short) 0x80)); // -32768",
),
(
"Math.multiplyHigh",
"Static Library",
"long Math.multiplyHigh(long x, long y) | long Math.unsignedMultiplyHigh(long x, long y)",
"The upper 64 bits of the exact 128-bit product, read as signed or (the `unsigned` form) unsigned operands.",
"System.out.println(Math.multiplyHigh(Long.MAX_VALUE, 3)); // 1",
),
(
"Double.toHexString",
"Static Library",
"String Double.toHexString(double d) | String Float.toHexString(float f)",
"The exact hexadecimal form: `0x1.` and the significand with trailing zeros dropped for a normal value, `0x0.` with the fixed `p-1022` (`p-126` for a `float`) exponent for a subnormal, and `NaN`, `Infinity` and a signed `0x0.0p0` spelled out. `Double.parseDouble`/`Float.parseFloat` and the hexadecimal floating-point literals (`0x1.8p1`) read the same notation back, rounding once.",
"System.out.println(Double.toHexString(0.1)); // 0x1.999999999999ap-4",
),
(
"Character.toTitleCase",
"Static Library",
"char Character.toTitleCase(char ch) | int Character.toTitleCase(int codePoint)",
"UnicodeData's simple titlecase mapping: the uppercase mapping except for the Latin digraphs (`dž` becomes `Dž`) and the Georgian letters, which title-case to themselves. Like `toUpperCase`/`toLowerCase`, the `int` overload answers an `int`.",
"System.out.println(Character.toTitleCase('a')); // A",
),
(
"Boolean.valueOf",
"Static Library",
"Boolean Boolean.valueOf(boolean b) | Boolean Boolean.valueOf(String s)",
"One of the two cached boxes `Boolean.TRUE`/`Boolean.FALSE`; the `String` form is `parseBoolean`, so only a case-insensitive `\"true\"` gives `TRUE` and `null` gives `FALSE`.",
"System.out.println(Boolean.valueOf(\"TrUe\")); // true",
),
(
"Integer.highestOneBit",
"Static Library",
"int Integer.highestOneBit(int i) | int Integer.lowestOneBit(int i)",
"The isolated highest or lowest set bit — a value with at most one bit set, not its index. Zero has no set bit, so both answer 0 for it. `Long` overloads answer at 64 bits.",
"System.out.println(Integer.highestOneBit(100) + \" \" + Integer.lowestOneBit(12)); // 64 4",
),
(
"Integer.numberOfLeadingZeros",
"Static Library",
"int Integer.numberOfLeadingZeros(int i) | int Integer.numberOfTrailingZeros(int i)",
"The count of zero bits above the highest, or below the lowest, set bit. A zero argument answers the full width — 32 for `Integer`, 64 for `Long`.",
"System.out.println(Integer.numberOfTrailingZeros(8)); // 3",
),
(
"Integer.rotateLeft",
"Static Library",
"int Integer.rotateLeft(int i, int distance) | int Integer.rotateRight(int i, int distance)",
"A circular shift: bits leaving one end re-enter at the other. The distance is taken modulo the width and a negative distance rotates the other way, so `Integer.rotateLeft(1, 33)` is 2 and `Integer.rotateLeft(1, -1)` is `Integer.MIN_VALUE`.",
"System.out.println(Integer.rotateLeft(1, 33)); // 2",
),
(
"Integer.sum",
"Static Library",
"int Integer.sum(int a, int b) | long Long.sum(long a, long b)",
"Addition at the declared width, which is the whole reason the two exist separately: `Integer.sum(Integer.MAX_VALUE, 1)` wraps to `Integer.MIN_VALUE` where `Long.sum` of the same operands is 2147483648. `max`/`min`/`signum`/`compare` are the same shape.",
"System.out.println(Integer.sum(Integer.MAX_VALUE, 1)); // -2147483648",
),
(
"Objects.hashCode",
"Static Library",
"int Objects.hashCode(Object o) | int Objects.hash(Object... values)",
"`hashCode` is the argument's own hash, or 0 for a null — a collection hashes by its contents, and a user class through its own `hashCode()`. `hash` folds a varargs array the way `Arrays.hashCode` does, seeded at 1, so `Objects.hash()` is 1 and `Objects.hash((Object) null)` is 31.",
"System.out.println(Objects.hashCode(null) + \" \" + Objects.hash(\"a\", \"b\")); // 0 4066",
),
(
"Objects.toString",
"Static Library",
"String Objects.toString(Object o) | String Objects.toString(Object o, String nullDefault)",
"The argument rendered as `println` would render it, reaching a user `toString()`. A null renders as the four-character string `null`, or as `nullDefault` when the two-argument form supplies one.",
"System.out.println(Objects.toString(null, \"none\")); // none",
),
(
"Objects.requireNonNull",
"Static Library",
"T Objects.requireNonNull(T o) | T Objects.requireNonNull(T o, String message) | T Objects.requireNonNullElse(T o, T other)",
"`requireNonNull` returns its argument or throws `NullPointerException` — with no detail message, or with the caller's text. `requireNonNullElse` returns the first non-null of the two and throws naming `defaultObj` when both are null.",
"System.out.println(Objects.requireNonNullElse(null, \"fallback\")); // fallback",
),
(
"Objects.isNull",
"Static Library",
"boolean Objects.isNull(Object o) | boolean Objects.nonNull(Object o)",
"The null test as a value, for use as a predicate. `Objects.equals(a, b)` is the matching equality test: `a == b || (a != null && a.equals(b))`, so it reaches a user `equals` and answers for a null receiver.",
"System.out.println(Objects.isNull(null) + \" \" + Objects.nonNull(null)); // true false",
),
// ── Collection Types: `collection_kind` / `is_concrete_collection` ──
(
"ArrayList",
"Collection Types",
"new ArrayList<>() | new ArrayList<>(other)",
"A mutable `List`, stored as a vector of values in list order. The copy constructor seeds it from any sequence-shaped argument — an array, a `List`, or a `Set` in that set's presentation order.",
"List<String> xs = new ArrayList<>();\nxs.add(\"a\");",
),
(
"LinkedList",
"Collection Types",
"new LinkedList<>() | new LinkedList<>(other)",
"Constructible, and backed by the same vector `ArrayList` uses. javars models the `List` contract, not the node-per-element representation, so the two differ only in name. The `Deque`/`Queue` methods work on it, head at index 0.",
"List<Integer> q = new LinkedList<>();",
),
(
"ArrayDeque",
"Collection Types",
"new ArrayDeque<>() | new ArrayDeque<>(other)",
"A double-ended queue, on the same vector the lists use with the head at index 0. Every `Deque`/`Queue` method produces the reference's element order and its empty-receiver behaviour, and the add family refuses a `null` element with `NullPointerException` as the JDK's does. What the shared shape cannot carry is the class: `getClass()` names `ArrayList`.",
"Deque<Integer> q = new ArrayDeque<>();\\nq.push(1);\\nq.addLast(2);\\nSystem.out.println(q); // [1, 2]",
),
(
"Stack",
"Collection Types",
"new Stack<>() | new Vector<>() | new Vector<>(int capacity) | new Vector<>(other)",
"`java.util.Stack` and the `Vector` it extends, on the same vector the lists use with the top of a `Stack` at the end — so it iterates and prints bottom first, as the JDK's does. `push` returns its argument; `pop`/`peek` on an empty stack throw `EmptyStackException`; `search` is the 1-based distance from the top, or -1. `Vector`'s own members (`elementAt`, `firstElement`/`lastElement`, `addElement`, `insertElementAt`, `removeElementAt`, `setElementAt`, `removeElement`, `removeAllElements`, `capacity`) and its index messages are the JDK's, including a negative index naming the backing array's capacity, which grows as the JDK's does.",
"Stack<Integer> s = new Stack<>();\\ns.push(1);\\ns.push(2);\\nSystem.out.println(s.pop() + \" \" + s + \" \" + s.search(1)); // 2 [1] 1",
),
(
"PriorityQueue",
"Collection Types",
"new PriorityQueue<>() | new PriorityQueue<>(cmp) | new PriorityQueue<>(cap, cmp) | new PriorityQueue<>(collection)",
"The JDK's binary heap, laid out by its own `siftUp`/`siftDown`/`heapify`, so `toString` and iteration show the heap array's order, not a sorted one. `poll`/`remove()` take the least element by the comparator (natural order when none is given, `comparator()` then answering `null`); a `PriorityQueue` seed hands over its comparator. The iterator's `remove()` follows `PriorityQueue.Itr`, deferring a lifted element to the end of the walk.",
"PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 4, 2));\\nSystem.out.println(pq + \" \" + pq.poll() + \" \" + pq); // [1, 2, 4, 5] 1 [2, 5, 4]",
),
(
"Deque",
"Collection Types",
"Deque<T> q = new ArrayDeque<>()",
"The declaration-only interface an `ArrayDeque` or `LinkedList` satisfies. Like `List` and `Map` it cannot be constructed directly.",
"Deque<String> q = new ArrayDeque<>();",
),
(
"Queue",
"Collection Types",
"Queue<T> q = new ArrayDeque<>()",
"The declaration-only single-ended view of the same shape: `offer` adds at the tail and `poll`/`peek` read the head.",
"Queue<String> q = new LinkedList<>();",
),
(
"HashMap",
"Collection Types",
"new HashMap<>() | new HashMap<>(other)",
"A `Map` whose iteration and `toString` order reproduce Java's real bucket order: entries are laid out in a power-of-two table indexed by `(capacity - 1) & (h ^ (h >>> 16))`, which makes the order a stable sort of the insertion sequence by bucket. Verified against OpenJDK 26 for `String` and `Integer` keys, including across the resize at 13 entries.",
"Map<String,Integer> m = new HashMap<>();\nm.put(\"one\", 1);",
),
(
"LinkedHashMap",
"Collection Types",
"new LinkedHashMap<>() | new LinkedHashMap<>(other)",
"A `Map` that iterates in insertion order. Since javars always *stores* entries in insertion order, this implementation is the one that costs nothing extra.",
"Map<String,Integer> m = new LinkedHashMap<>();",
),
(
"TreeMap",
"Collection Types",
"new TreeMap<>() | new TreeMap<>(other)",
"A `Map` that iterates in ascending natural key order: numbers numerically, strings lexicographically by `char`, `null` first. The key-navigation methods (`firstKey`, `floorKey`, `ceilingEntry`, `pollFirstEntry`, …) are implemented; the range views (`headMap`, `tailMap`, `descendingMap`, …) are not.",
"Map<String,Integer> m = new TreeMap<>();",
),
(
"HashSet",
"Collection Types",
"new HashSet<>() | new HashSet<>(other)",
"A `Set` with `HashMap`'s bucket iteration order. Building one from a sequence keeps the first of each repeated value.",
"Set<String> s = new HashSet<>();\ns.add(\"a\");",
),
(
"LinkedHashSet",
"Collection Types",
"new LinkedHashSet<>() | new LinkedHashSet<>(other)",
"A `Set` that iterates in insertion order.",
"Set<String> s = new LinkedHashSet<>();",
),
(
"TreeSet",
"Collection Types",
"new TreeSet<>() | new TreeSet<>(other)",
"A `Set` that iterates in ascending natural order of its elements.",
"Set<String> s = new TreeSet<>();\ns.add(\"z\"); s.add(\"a\");\nSystem.out.println(s); // [a, z]",
),
(
"List",
"Collection Types",
"List<T> name = …; | List.of(…)",
"Declaration-only: the interface types the variable but cannot be instantiated — `new List<>()` is not a thing in Java either. A user class named `List` wins over this modeling, so declaring your own is still legal.",
"List<String> xs = new ArrayList<>();",
),
(
"Collection",
"Collection Types",
"Collection<T> name = …;",
"Declaration-only, treated as a list-shaped receiver for the purpose of typing a call's result.",
"Collection<String> c = new ArrayList<>();",
),
(
"Iterable",
"Collection Types",
"Iterable<T> name = …;",
"Declaration-only, list-shaped. An enhanced `for` over any collection works through the `JITER_ARRAY` builtin regardless of the declared type; there is no `Iterator` object to obtain.",
"Iterable<String> it = new ArrayList<>();",
),
(
"AbstractMap.SimpleEntry",
"Collection Types",
"new AbstractMap.SimpleEntry<>(k, v) | new AbstractMap.SimpleEntry<>(entry) | new AbstractMap.SimpleImmutableEntry<>(…)",
"A `Map.Entry` that belongs to no map: `getKey`/`getValue`, `equals`/`hashCode`/`toString` as every entry has them, and `null` accepted on either side. `SimpleEntry.setValue` replaces its own value and answers the old one; `SimpleImmutableEntry.setValue` is `UnsupportedOperationException`. The one-argument form copies any entry's key and value.",
"var e = new AbstractMap.SimpleEntry<>(\"k\", 1);\\ne.setValue(2);\\nSystem.out.println(e); // k=2",
),
(
"Map",
"Collection Types",
"Map<K,V> name = …;",
"Declaration-only. The map methods available on the variable are the ones the modeled implementations provide, `entrySet` among them — it answers a set of `Map.Entry` objects, one per key, that read through to the map.",
"Map<String,Integer> m = new HashMap<>();",
),
(
"Set",
"Collection Types",
"Set<T> name = …; | Set.of(…)",
"Declaration-only as a type, though `Set.of` is a usable static factory.",
"Set<String> s = new HashSet<>();",
),
// ── Collection Statics: `host.rs` `collection_static` ──
(
"Arrays.asList",
"Collection Statics",
"List<T> Arrays.asList(T... a)",
"A *fixed-size* list view: `set` replaces an element, but `add`, `remove`, and `clear` raise `UnsupportedOperationException` exactly as Java's does. A lone array argument spreads into its elements rather than becoming a one-element list, matching Java's varargs rule for reference arrays.",
"List<Integer> xs = Arrays.asList(1, 2, 3);\nxs.set(0, 9); // fine\n// xs.add(4); // UnsupportedOperationException",
),
(
"List.of",
"Collection Statics",
"List<T> List.of(T... elements)",
"A fully immutable list: every structural change *and* every element replacement raises `UnsupportedOperationException`.",
"System.out.println(List.of(1, 2, 3)); // [1, 2, 3]",
),
(
"Set.of",
"Collection Statics",
"Set<T> Set.of(T... elements)",
"An immutable set with `HashSet` iteration order, keeping the first of each repeated element.",
"System.out.println(Set.of(\"p\")); // [p]",
),
(
"Collections.sort",
"Collection Statics",
"void Collections.sort(List<T> list)",
"Sorts the list in place into ascending natural order — the elements' own `compareTo`, so a list of a user `Comparable` sorts by its method — and the change is visible through every reference to it.",
"Collections.sort(xs);",
),
(
"Collections.sort",
"Collection Statics",
"void Collections.sort(List<T> list, Comparator<T> cmp)",
"Sorts in place with a comparator lambda. The sort is a bottom-up merge sort that never panics on an inconsistent comparator and is stable, as Java guarantees for `List.sort`. A `null` comparator means natural order.",
"Collections.sort(xs, (a, b) -> a.length() - b.length());",
),
(
"Collections.reverse",
"Collection Statics",
"void Collections.reverse(List<T> list)",
"Reverses the list in place.",
"Collections.reverse(xs);",
),
(
"EnumSet",
"Collection Statics",
"EnumSet.of(E e, E... rest) | EnumSet.noneOf(Class<E>) | EnumSet.allOf(Class<E>) | EnumSet.copyOf(Collection<E>)",
"An enum set, iterating in ordinal order. javars models it as the `TreeSet` it behaves as (an enum's natural order is its ordinal order), so it prints, orders and answers queries as the JDK's does; `getClass()` names `java.util.TreeSet`. `range` and `complementOf` read the constants off the static enum type, so their argument has to have one.",
"System.out.println(EnumSet.of(Day.SUN, Day.MON)); // [MON, SUN]",
),
(
"EnumMap",
"Collection Statics",
"new EnumMap<>(Class<K> keyType) | new EnumMap<>(Map<K, V> m)",
"A map keyed by an enum, iterating in ordinal order — modeled as the `TreeMap` it behaves as.",
"Map<Day, Integer> h = new EnumMap<>(Day.class);",
),
(
"Map.Entry.comparingByKey",
"Collection Statics",
"Comparator Map.Entry.comparingByKey([Comparator cmp]) | Map.Entry.comparingByValue([Comparator cmp])",
"The comparators that order map entries by key or by value — natural order, or `cmp` applied to the key or value.",
"entries.sort(Map.Entry.comparingByValue());",
),
(
"Collections.shuffle",
"Collection Statics",
"void Collections.shuffle(List<?> list [, Random rnd])",
"Permutes the list in place by the JDK's walk — `swap(list, i - 1, rnd.nextInt(i))` from the size down to 2 — so a seeded `Random` gives the JDK's order. Without one, an unseeded generator of its own is used.",
"Collections.shuffle(xs, new Random(7));",
),
(
"Collections.frequency",
"Collection Statics",
"int Collections.frequency(Collection<?> c, Object o)",
"How many elements `o.equals` — or how many are `null` when `o` is — calling the element class's own `equals`.",
"int twos = Collections.frequency(xs, 2);",
),
(
"Collections.swap",
"Collection Statics",
"void Collections.swap(List<?> list, int i, int j)",
"Exchanges two positions as `l.set(i, l.set(j, l.get(i)))`, so an out-of-range index and an immutable list fail exactly as `get`/`set` do.",
"Collections.swap(xs, 0, xs.size() - 1);",
),
(
"Collections.binarySearch",
"Collection Statics",
"int Collections.binarySearch(List<T> list, T key [, Comparator<T> cmp])",
"The index of `key` in a list sorted by `cmp` (natural order when absent or `null`, through the elements' own `compareTo`), or `-(insertion point) - 1` when it is absent.",
"int at = Collections.binarySearch(List.of(1, 3, 5), 4); // -3",
),
(
"Collections.disjoint",
"Collection Statics",
"boolean Collections.disjoint(Collection<?> c1, Collection<?> c2)",
"True when the two collections share no element. One side is iterated and the other's `contains` asked, chosen as the JDK chooses (a `Set` is the one asked), so each side's own membership rules apply.",
"boolean none = Collections.disjoint(xs, Set.of(9));",
),
(
"Collections.rotate",
"Collection Statics",
"void Collections.rotate(List<?> list, int distance)",
"Moves the element at `i` to `(i + distance) mod size`; a negative distance rotates left. Written with `set`, so a `subList` view of the list stays valid.",
"Collections.rotate(xs, 2); // [1, 2, 3, 4, 5] → [4, 5, 1, 2, 3]",
),
(
"Collections.fill",
"Collection Statics",
"void Collections.fill(List<? super T> list, T obj)",
"Sets every position to `obj`.",
"Collections.fill(xs, 0);",
),
(
"Collections.indexOfSubList",
"Collection Statics",
"int Collections.indexOfSubList(List<?> source, List<?> target) | Collections.lastIndexOfSubList(List<?> source, List<?> target)",
"The first (or last) position at which `target` occurs as a contiguous run of `source`, compared by `equals`; `-1` when it does not occur. An empty `target` matches at 0 (or at `source.size()`).",
"int at = Collections.indexOfSubList(List.of(1, 2, 3, 2, 3), List.of(2, 3)); // 1",
),
(
"Collections.reverseOrder",
"Collection Statics",
"Comparator<T> Collections.reverseOrder() | Collections.reverseOrder(Comparator<T> cmp)",
"The comparator that imposes the reverse of natural order — `Comparator.reverseOrder()` — or the reverse of `cmp` (`cmp.reversed()`). A `null` argument means natural order, as the JDK specifies.",
"xs.sort(Collections.reverseOrder());",
),
(
"Collections.max",
"Collection Statics",
"T Collections.max(Collection<T> c [, Comparator<T> cmp])",
"The largest element in ascending natural order — the elements' own `compareTo`, so a user `Comparable` orders by its body — or by `cmp`. An empty collection raises `java.util.NoSuchElementException`, catchable like any modeled throwable.",
"System.out.println(Collections.max(xs));",
),
(
"Collections.min",
"Collection Statics",
"T Collections.min(Collection<T> c [, Comparator<T> cmp])",
"The smallest element in ascending natural order; empty raises the same `NoSuchElementException` as `Collections.max`.",
"System.out.println(Collections.min(xs));",
),
// ── List Methods: `host.rs` `list_method`, plus the three handled in
// `coll_method` before the heap borrow is taken ──
(
"size",
"List Methods",
"int size()",
"The number of elements.",
"System.out.println(xs.size());",
),
(
"isEmpty",
"List Methods",
"boolean isEmpty()",
"True when the list holds no elements.",
"if (xs.isEmpty()) { System.out.println(\"none\"); }",
),
(
"add",
"List Methods",
"boolean add(T e)",
"Appends an element and returns `true`. On a fixed-size or immutable list this raises `UnsupportedOperationException` rather than succeeding silently.",
"xs.add(\"c\");",
),
(
"add",
"List Methods",
"void add(int index, T e)",
"Inserts at `index`, shifting the tail right. An index outside `[0, size]` raises `IndexOutOfBoundsException` with Java's `Index: i, Size: n` message — the distinct wording this overload uses.",
"xs.add(0, \"first\");",
),
(
"get",
"List Methods",
"T get(int index)",
"The element at `index`. Out of range raises what the receiver's shape raises: an `ArrayList` gives `IndexOutOfBoundsException: Index i out of bounds for length n`, `Arrays.asList` and a `List.of` of three or more elements give `ArrayIndexOutOfBoundsException` with that same message, and a `List.of` of one or two gives `IndexOutOfBoundsException: Index: i Size: n`.",
"System.out.println(xs.get(0));",
),
(
"set",
"List Methods",
"T set(int index, T e)",
"Replaces the element at `index` and returns the previous value. Permitted on a fixed-size list (that is what `Arrays.asList` gives you) and refused on an immutable one.",
"xs.set(0, \"z\");",
),
(
"remove",
"List Methods",
"T remove(int index) | boolean remove(Object o)",
"Both of Java's overloads, chosen at compile time from the argument's *static* type exactly as `javac` chooses them: an `int`/`short`/`byte`/`char` argument removes and returns the element at that index, and any reference argument — a boxed `Integer`, an `Integer.valueOf(x)`, a `String` — removes the first element equal to it and answers whether one was found. An argument javars cannot type statically keeps the by-index reading.",
"xs.remove(0); // by index\nxs.remove(Integer.valueOf(20)); // by value",
),
(
"subList",
"List Methods",
"List<T> subList(int fromIndex, int toIndex)",
"A **view** of the half-open range, not a copy: it owns no elements, so writes cross in both directions — `list.set(i, v)` shows through the view and `view.set(i, v)` shows in the list — and `view.add`/`remove`/`clear` splice the backing list itself. A view of a view composes offsets down to the same list. Structurally modifying the backing list *behind* an outstanding view invalidates it, and the next operation on it (or rendering it) raises `ConcurrentModificationException`. `fromIndex < 0` or `toIndex > size()` is an `IndexOutOfBoundsException` naming the offending index; `fromIndex > toIndex` is an `IllegalArgumentException`.",
"List<Integer> l = new ArrayList<>(List.of(10, 20, 30, 40));\nList<Integer> v = l.subList(1, 3);\nv.set(0, 99);\nSystem.out.println(l); // [10, 99, 30, 40]",
),
(
"clear",
"List Methods",
"void clear()",
"Removes every element. Structural, so it is refused on a fixed-size or immutable list.",
"xs.clear();",
),
(
"contains",
"List Methods",
"boolean contains(Object o)",
"True when some element equals `o` by value for strings, numbers, and booleans, or by handle identity for a heap object. A user `equals` override is not consulted.",
"System.out.println(xs.contains(\"a\"));",
),
(
"indexOf",
"List Methods",
"int indexOf(Object o)",
"The index of the first matching element, or `-1`.",
"System.out.println(xs.indexOf(\"a\"));",
),
(
"lastIndexOf",
"List Methods",
"int lastIndexOf(Object o)",
"The index of the last matching element, or `-1`.",
"System.out.println(xs.lastIndexOf(\"a\"));",
),
(
"addAll",
"List Methods",
"boolean addAll(Collection<T> other)",
"Appends every element of `other` in its presentation order and returns whether anything was added. The argument is snapshotted before the receiver's heap borrow is taken, so `xs.addAll(xs)` is well defined.",
"xs.addAll(ys);",
),
(
"equals",
"List Methods",
"boolean equals(Object other)",
"Element-wise equality against another sequence of the same length.",
"System.out.println(xs.equals(ys));",
),
(
"sort",
"List Methods",
"void sort(Comparator<T> cmp)",
"Sorts in place with a comparator lambda, or in natural order when given `null`. Handled before the heap borrow is taken, because the comparator body is user code that may allocate.",
"xs.sort((a, b) -> a.length() - b.length());",
),
(
"forEach",
"List Methods",
"void forEach(Consumer<T> action)",
"Invokes the action once per element, in order. Like `sort`, the elements are snapshotted first so the lambda body can safely allocate.",
"xs.forEach(x -> System.out.println(x));",
),
(
"toString",
"List Methods",
"String toString()",
"`AbstractCollection.toString` — `[a, b, c]`, each element rendered with Java's value-to-string rules. This is also what `System.out.println(list)` prints, without any explicit call.",
"System.out.println(xs); // [a, b, c]",
),
(
"removeIf",
"List Methods",
"boolean removeIf(Predicate<? super T> filter)",
"Removes every element the predicate accepts and answers whether any went. The receiver's shape decides the refusal: an immutable `List.of`/`Set.of` throws `UnsupportedOperationException` before it looks at the argument, while a fixed-size `Arrays.asList` runs the predicate and throws — with the message `remove` its iterator names — only when something must actually go. Through a `subList` the removal reaches the backing list and leaves the view usable.",
"List<Integer> xs = new ArrayList<>(List.of(1, 2, 3, 4));\\nxs.removeIf(x -> x % 2 == 0);\\nSystem.out.println(xs); // [1, 3]",
),
(
"removeAll",
"List Methods",
"boolean removeAll(Collection<?> c)",
"Removes every element that `c` contains — `e.equals(x)` for some `x` of `c` — and answers whether any went. Lists and sets alike; the refusals are `removeIf`'s, and a `null` argument is a `NullPointerException`.",
"List<Integer> xs = new ArrayList<>(List.of(1, 2, 3, 2));\\nxs.removeAll(List.of(2));\\nSystem.out.println(xs); // [1, 3]",
),
(
"retainAll",
"List Methods",
"boolean retainAll(Collection<?> c)",
"Keeps only the elements `c` contains and answers whether any went, with `removeAll`'s refusals.",
"List<Integer> xs = new ArrayList<>(List.of(1, 2, 3));\\nxs.retainAll(Set.of(1, 3));\\nSystem.out.println(xs); // [1, 3]",
),
(
"containsAll",
"List Methods",
"boolean containsAll(Collection<?> c)",
"True when every element of `c` equals some element of the receiver; an empty `c` is contained in anything.",
"System.out.println(List.of(1, 2, 3).containsAll(List.of(3, 1))); // true",
),
(
"replaceAll",
"List Methods",
"void replaceAll(UnaryOperator<T> operator)",
"Rewrites every element in place. It counts as a structural modification whether or not any element changed, so an outstanding `subList` view of the receiver is stale afterwards. An immutable list refuses; a fixed-size one accepts, since the length does not change.",
"List<Integer> xs = new ArrayList<>(List.of(1, 2));\\nxs.replaceAll(x -> x * 10);\\nSystem.out.println(xs); // [10, 20]",
),
(
"addFirst",
"List Methods",
"void addFirst(T e) | void addLast(T e) | void push(T e) | boolean offer(T e) | boolean offerFirst(T e) | boolean offerLast(T e)",
"The `Deque` writers. `addFirst`/`offerFirst`/`push` insert at the head, `addLast`/`offerLast`/`offer` append at the tail — so a stack built with `push` reads back in reverse. The `offer` spellings answer `true`.",
"Deque<Integer> q = new ArrayDeque<>();\\nq.push(1);\\nq.push(2);\\nSystem.out.println(q); // [2, 1]",
),
(
"peekFirst",
"List Methods",
"T getFirst() | T getLast() | T element() | T peek() | T peekFirst() | T peekLast()",
"The `Deque` readers, which do not remove. On an empty receiver the two families part: `getFirst`/`getLast`/`element` throw `NoSuchElementException` where `peek`/`peekFirst`/`peekLast` answer `null`.",
"Deque<Integer> q = new ArrayDeque<>(List.of(1, 2));\\nSystem.out.println(q.peekFirst() + \" \" + q.peekLast()); // 1 2",
),
(
"pollFirst",
"List Methods",
"T pop() | T poll() | T pollFirst() | T pollLast() | T removeFirst() | T removeLast()",
"The `Deque` readers that remove, on the same split: `pop`/`removeFirst`/`removeLast` throw `NoSuchElementException` on an empty receiver where `poll`/`pollFirst`/`pollLast` answer `null`. `pop` and `poll` both take the head; only the empty case tells them apart.",
"Deque<Integer> q = new ArrayDeque<>(List.of(1, 2, 3));\\nSystem.out.println(q.pollFirst() + \" \" + q.pollLast()); // 1 3",
),
(
"descendingIterator",
"List Methods",
"Iterator<T> descendingIterator()",
"`Deque`'s and `NavigableSet`'s reverse walk, on a `LinkedList`, an `ArrayDeque` or a `TreeSet`: `next` returns the elements last to first, and `remove` deletes the one it returned. A structural change behind it is `ConcurrentModificationException`.",
"Deque<Integer> q = new ArrayDeque<>(List.of(1, 2, 3));\\nIterator<Integer> it = q.descendingIterator();\\nwhile (it.hasNext()) System.out.print(it.next()); // 321",
),
(
"listIterator",
"List Methods",
"ListIterator<T> listIterator() | ListIterator<T> listIterator(int index)",
"A cursor over the list that walks both ways (`next`/`previous`, `nextIndex`/`previousIndex`) and writes at the cursor: `set` replaces the element last returned, `add` inserts before the cursor, `remove` deletes. A start outside `[0, size]` is `IndexOutOfBoundsException: Index: n, Size: s`; a structural change behind it is `ConcurrentModificationException`.",
"List<Integer> l = new ArrayList<>(List.of(1, 2, 3));\\nListIterator<Integer> it = l.listIterator(l.size());\\nwhile (it.hasPrevious()) { int v = it.previous(); it.set(v * 10); }\\nSystem.out.println(l); // [10, 20, 30]",
),
(
"toArray",
"List Methods",
"Object[] toArray() | T[] toArray(T[] a) | T[] toArray(IntFunction<T[]> gen)",
"The elements as an array, on any `List`, `Set`, `Deque`, or `PriorityQueue`. An argument at least as long as the collection is filled in place and returned, with the slot past the last element set to `null`; a shorter one only names the type.",
"String[] arr = List.of(\"a\", \"b\").toArray(String[]::new);\\nSystem.out.println(arr.length); // 2",
),
// ── Map Methods: `host.rs` `map_method`, plus `forEach`/`toString` ──
(
"headMap",
"Map Methods",
"headMap(to [, incl]) | tailMap(from [, incl]) | subMap(from, to) | subMap(from, fi, to, ti) | descendingMap() | navigableKeySet() | descendingKeySet()",
"A `TreeMap`'s range and descending views: `head` excludes its key unless `incl`, `tail` includes it, `sub` is `[from, to)`; a `null` bound is `NullPointerException` and `from > to` `IllegalArgumentException: fromKey > toKey`. A descending view iterates and navigates in reverse. javars returns a copy whose removals (`remove`, `clear`, `pollFirstEntry`, …) reach the source map; an insertion through one is refused.",
"System.out.println(new TreeMap<>(Map.of(1, \"a\", 5, \"e\", 3, \"c\")).headMap(4)); // {1=a, 3=c}",
),
(
"size",
"Map Methods",
"int size()",
"The number of entries.",
"System.out.println(m.size());",
),
(
"isEmpty",
"Map Methods",
"boolean isEmpty()",
"True when the map holds no entries.",
"if (m.isEmpty()) { System.out.println(\"empty\"); }",
),
(
"put",
"Map Methods",
"V put(K key, V value)",
"Associates `key` with `value` and returns the previous value, or `null` when the key was absent. Re-putting an existing key keeps the entry's original insertion position, which is what Java's linked and bucket layouts both do.",
"m.put(\"one\", 1);",
),
(
"putIfAbsent",
"Map Methods",
"V putIfAbsent(K key, V value)",
"Inserts only when the key is absent; returns the existing value when it was present, `null` otherwise.",
"m.putIfAbsent(\"one\", 99);",
),
(
"get",
"Map Methods",
"V get(Object key)",
"The value for `key`, or `null` when absent. Keys are matched with the same value-or-identity equality the rest of the collections use.",
"System.out.println(m.get(\"one\"));",
),
(
"getOrDefault",
"Map Methods",
"V getOrDefault(Object key, V fallback)",
"The value for `key`, or `fallback` when the key is absent.",
"System.out.println(m.getOrDefault(\"nope\", 0)); // 0",
),
(
"containsKey",
"Map Methods",
"boolean containsKey(Object key)",
"True when the map holds an entry for `key`.",
"System.out.println(m.containsKey(\"one\"));",
),
(
"containsValue",
"Map Methods",
"boolean containsValue(Object value)",
"True when some entry's value matches — a linear scan, as in Java.",
"System.out.println(m.containsValue(1));",
),
(
"remove",
"Map Methods",
"V remove(Object key)",
"Removes the entry and returns its value, or `null` when the key was absent.",
"m.remove(\"one\");",
),
(
"clear",
"Map Methods",
"void clear()",
"Removes every entry.",
"m.clear();",
),
(
"keySet",
"Map Methods",
"Set<K> keySet()",
"A `Set` of the keys, already materialized in the map's own presentation order — so it iterates and prints exactly as the map does. It is a snapshot, not a live view: removing from it does not change the map.",
"System.out.println(m.keySet());",
),
(
"values",
"Map Methods",
"Collection<V> values()",
"A fixed-size list of the values, in the map's presentation order and therefore aligned position-for-position with `keySet()`. Also a snapshot.",
"System.out.println(m.values());",
),
(
"forEach",
"Map Methods",
"void forEach(BiConsumer<K,V> action)",
"Invokes a two-argument action per entry, in presentation order. The map's `forEach` is distinguished from a list's by the receiver, so the same lambda arity rules as Java apply.",
"m.forEach((k, v) -> System.out.println(k + \"=\" + v));",
),
(
"toString",
"Map Methods",
"String toString()",
"`AbstractMap.toString` — `{k=v, k=v}` in presentation order, which for a `HashMap` is Java's real bucket order.",
"System.out.println(m); // {one=1, two=2, three=3}",
),
// ── Set Methods: `host.rs` `set_method`, plus `forEach`/`toString` ──
(
"firstKey",
"Map Methods",
"K firstKey() | K lastKey()",
"A `TreeMap`'s lowest or highest key in its sorted order. An empty map raises `NoSuchElementException`.",
"TreeMap<Integer,String> t = new TreeMap<>(Map.of(1, \"a\", 5, \"e\"));\nSystem.out.println(t.firstKey() + \" \" + t.lastKey()); // 1 5",
),
(
"floorKey",
"Map Methods",
"K floorKey(K k) | ceilingKey | lowerKey | higherKey",
"A `TreeMap`'s greatest key `<=` / least key `>=` / greatest key `<` / least key `>` the probe, or `null` when there is none. A `null` probe is `NullPointerException` once the map has a key to compare it with.",
"System.out.println(t.floorKey(4) + \" \" + t.higherKey(5)); // 1 null",
),
(
"firstEntry",
"Map Methods",
"Map.Entry<K,V> firstEntry() | lastEntry | floorEntry(K) | ceilingEntry(K) | lowerEntry(K) | higherEntry(K)",
"The key-navigation methods' pairs: an immutable snapshot whose `setValue` is `UnsupportedOperationException`, or `null` when there is no such key — an empty map included.",
"System.out.println(t.ceilingEntry(2)); // 5=e",
),
(
"pollFirstEntry",
"Map Methods",
"Map.Entry<K,V> pollFirstEntry() | pollLastEntry()",
"Removes and answers the lowest or highest entry of a `TreeMap`, or `null` when it is empty.",
"while (!t.isEmpty()) System.out.println(t.pollFirstEntry());",
),
(
"headSet",
"Set Methods",
"headSet(to [, incl]) | tailSet(from [, incl]) | subSet(from, to) | subSet(from, fi, to, ti) | descendingSet()",
"A `TreeSet`'s range and descending views, on the same bound rules and copy terms as `TreeMap.headMap`.",
"System.out.println(new TreeSet<>(List.of(5, 1, 3)).tailSet(3)); // [3, 5]",
),
(
"size",
"Set Methods",
"int size()",
"The number of distinct elements.",
"System.out.println(s.size());",
),
(
"isEmpty",
"Set Methods",
"boolean isEmpty()",
"True when the set holds no elements.",
"if (s.isEmpty()) { System.out.println(\"empty\"); }",
),
(
"add",
"Set Methods",
"boolean add(T e)",
"Adds the element if it is not already present, returning whether the set changed.",
"System.out.println(s.add(\"a\")); // true the first time",
),
(
"contains",
"Set Methods",
"boolean contains(Object o)",
"Membership test, by value for strings, numbers, and booleans and by handle identity for a heap object.",
"System.out.println(s.contains(\"a\"));",
),
(
"remove",
"Set Methods",
"boolean remove(Object o)",
"Removes the element if present, returning whether the set changed. Unlike `List.remove`, this overload is by value rather than by index.",
"s.remove(\"a\");",
),
(
"clear",
"Set Methods",
"void clear()",
"Removes every element.",
"s.clear();",
),
(
"addAll",
"Set Methods",
"boolean addAll(Collection<T> other)",
"Adds every element of `other` that is not already present, returning whether the set changed.",
"s.addAll(other);",
),
(
"forEach",
"Set Methods",
"void forEach(Consumer<T> action)",
"Invokes the action once per element, in the set's presentation order.",
"s.forEach(x -> System.out.println(x));",
),
(
"toString",
"Set Methods",
"String toString()",
"`[a, b, c]` in presentation order — bucket order for a `HashSet`, insertion order for a `LinkedHashSet`, ascending for a `TreeSet`.",
"System.out.println(s);",
),
(
"first",
"Set Methods",
"E first() | E last()",
"A `TreeSet`'s lowest or highest element. An empty set raises `NoSuchElementException`.",
"TreeSet<String> s = new TreeSet<>(List.of(\"pear\", \"fig\"));\nSystem.out.println(s.first()); // fig",
),
(
"floor",
"Set Methods",
"E floor(E e) | ceiling | lower | higher",
"A `TreeSet`'s greatest element `<=` / least `>=` / greatest `<` / least `>` the probe, or `null` when there is none.",
"System.out.println(s.ceiling(\"g\")); // pear",
),
(
"pollFirst",
"Set Methods",
"E pollFirst() | E pollLast()",
"Removes and answers a `TreeSet`'s lowest or highest element, or `null` when it is empty. On a `Deque` the same names are the deque's own methods.",
"System.out.println(s.pollLast()); // pear",
),
// ── Throwables: `prelude.rs` `THROWABLES`, written in Java and parsed with
// the ordinary parser, so `extends`, `super(m)`, virtual dispatch and
// `instanceof` all apply to them unchanged ──
(
"Throwable",
"Throwables",
"class Throwable { Throwable(); Throwable(String message); String getMessage(); String toString(); }",
"The root of the modeled hierarchy and the only class that carries state: a `detailMessage` field the whole tree inherits, its accessor, and a `toString()` that prints `java.lang.Throwable` alone or with `\": \" + detailMessage`. The no-argument constructor leaves the message at its field default, which is exactly the `null` Java's `getMessage()` returns.",
"throw new Throwable(\"root cause\");",
),
(
"Error",
"Throwables",
"class Error extends Throwable",
"Java's unchecked-error branch. javars never raises one itself; it exists so a program that throws or catches an `Error` compiles and runs.",
"catch (Error e) { System.out.println(e); }",
),
(
"Exception",
"Throwables",
"class Exception extends Throwable",
"The base of the checked branch, and the arm that catches everything javars raises. `catch (Exception e)` matching a `NumberFormatException` is just the `instanceof` supertype walk the runtime already performs.",
"try { risky(); } catch (Exception e) { System.out.println(e.getMessage()); }",
),
(
"RuntimeException",
"Throwables",
"class RuntimeException extends Exception",
"The unchecked branch, and the superclass of every fault the runtime raises.",
"throw new RuntimeException(\"boom\");",
),
(
"IllegalArgumentException",
"Throwables",
"class IllegalArgumentException extends RuntimeException",
"Raised by `String.repeat` with a negative count, carrying Java's `count is negative: n` message. Also throwable directly.",
"throw new IllegalArgumentException(\"bad input\");",
),
(
"NumberFormatException",
"Throwables",
"class NumberFormatException extends IllegalArgumentException",
"Raised by `Integer.parseInt`, `Integer.valueOf`, and `Long.parseLong` for a malformed string, an out-of-width value, or an out-of-range radix. The detail message is Java's own — `For input string: \"zz\"`, and the radix-qualified variant for a non-decimal radix.",
"try { Integer.parseInt(\"zz\"); } catch (NumberFormatException e) { System.out.println(e.getMessage()); }",
),
(
"IllegalStateException",
"Throwables",
"class IllegalStateException extends RuntimeException",
"Never raised by the runtime; supplied so program code can throw and catch it.",
"throw new IllegalStateException(\"bad state\");",
),
(
"ArithmeticException",
"Throwables",
"class ArithmeticException extends RuntimeException",
"Raised by integral `/` and `%` with a zero divisor, carrying Java's message `/ by zero` for both operators. The check is emitted inline by the compiler rather than by a builtin, so it costs one compare and one branch and stays JIT-traceable. Floating division never raises it — IEEE-754 gives an infinity instead.",
"try { int z = 0; System.out.println(1 / z); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } // / by zero",
),
(
"NullPointerException",
"Throwables",
"class NullPointerException extends RuntimeException",
"Raised on every null dereference javars models: an array load, store, or `.length`; an instance field read or assignment; a method call on a null receiver; unboxing a null wrapper; iterating a null; and invoking a null functional-interface target. Java's \"helpful\" messages name the bytecode local slot of the null reference (`because \"<local3>\" is null`), which javars has no javac slot numbering to reproduce, so it keeps the operation half of Java's wording and drops the provenance clause.",
"String s = null;\n// s.length(); // Cannot invoke \"String.length()\" because the receiver is null",
),
(
"ClassCastException",
"Throwables",
"class ClassCastException extends RuntimeException",
"Raised by a *checked* reference cast whose target the value's runtime class does not satisfy, with Java's own detail message. The cast changes no representation — the host heap already carries each object's class — so verifying one is all it does. Primitive casts are real conversions and cannot fail.",
"catch (ClassCastException e) { System.out.println(e); }",
),
(
"UnsupportedOperationException",
"Throwables",
"class UnsupportedOperationException extends RuntimeException",
"Raised by a structural change to a fixed-size list (`Arrays.asList`) or by any change at all to an immutable one (`List.of`). One divergence to know: javars constructs it with an empty string where Java leaves the message `null`, so `getMessage()` returns `\"\"` instead of `null` and `toString()` prints a trailing `\": \"` that Java omits.",
"List<Integer> xs = List.of(1, 2);\ntry { xs.add(3); } catch (UnsupportedOperationException e) { System.out.println(\"[\" + e.getMessage() + \"]\"); } // []",
),
(
"NegativeArraySizeException",
"Throwables",
"class NegativeArraySizeException extends RuntimeException",
"Raised by `new T[n]` and by the multi-dimensional form when any dimension is negative. The detail message is the offending size, as in Java.",
"try { int[] a = new int[-1]; } catch (NegativeArraySizeException e) { System.out.println(e.getMessage()); } // -1",
),
(
"IndexOutOfBoundsException",
"Throwables",
"class IndexOutOfBoundsException extends RuntimeException",
"Raised by the `List` accessors — `get`, `set`, `remove`, and the two-argument `add`. On a mutable list the first three carry `Index i out of bounds for length n`; `add(index, e)` carries Java's distinct `Index: i, Size: n` wording, and a one-or-two-element `List.of` carries `Index: i Size: n`. An array-backed receiver (`Arrays.asList`, a longer `List.of`) raises the `ArrayIndexOutOfBoundsException` subclass instead.",
"try { xs.get(99); } catch (IndexOutOfBoundsException e) { System.out.println(e.getMessage()); }",
),
(
"ArrayIndexOutOfBoundsException",
"Throwables",
"class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException",
"Raised by an out-of-range array read or write, and by the `List` shapes that index a backing array (`Arrays.asList`, a `List.of` of three or more elements), carrying Java's exact `Index i out of bounds for length n`. The bounds check runs inside the heap borrow and the throwable is allocated after it is released, since raising allocates on the same heap.",
"int[] a = new int[2];\ntry { System.out.println(a[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); }",
),
(
"StringIndexOutOfBoundsException",
"Throwables",
"class StringIndexOutOfBoundsException extends IndexOutOfBoundsException",
"Raised by `charAt` and both `substring` overloads. `charAt` carries `Index i out of bounds for length n`; `substring` carries `Range [b, e) out of bounds for length n`.",
"try { \"hi\".charAt(9); } catch (StringIndexOutOfBoundsException e) { System.out.println(e.getMessage()); }",
),
(
"ConcurrentModificationException",
"Throwables",
"class ConcurrentModificationException extends RuntimeException",
"Raised by a `List.subList` view whose backing list was structurally modified behind it — an `add`, a `remove`, or a `Collections.sort` (which bumps Java's `modCount` even though the length is unchanged). One of the modeled throwables outside `java.lang`, and prints as `java.util.ConcurrentModificationException`.",
"List<Integer> l = new ArrayList<>(List.of(1, 2, 3));\nList<Integer> v = l.subList(0, 2);\nl.add(4);\n// v.get(0); // ConcurrentModificationException",
),
(
"NoSuchElementException",
"Throwables",
"class NoSuchElementException extends RuntimeException",
"Raised by `Collections.max`/`min` on an empty collection. Java's carries no detail message there, and neither does this one; it prints as `java.util.NoSuchElementException`.",
"try { Collections.max(new ArrayList<>()); } catch (NoSuchElementException e) { System.out.println(e); }",
),
(
"InputMismatchException",
"Throwables",
"class InputMismatchException extends NoSuchElementException",
"Raised by a `Scanner` `nextInt`/`nextDouble`/… whose token is not of the requested type; the token stays unread. An integer token out of range carries `For input string: \"…\"`, any other none. Prints as `java.util.InputMismatchException`.",
"try { new Scanner(\"x\").nextInt(); } catch (InputMismatchException e) { System.out.println(e); }",
),
(
"IOException",
"Throwables",
"class IOException extends Exception",
"The checked `java.io` exception. A closed `BufferedReader` raises it as `java.io.IOException: Stream closed`; a `throws IOException` clause on `main` is accepted as Java requires it.",
"try { br.readLine(); } catch (IOException e) { System.out.println(e); }",
),
(
"AssertionError",
"Throwables",
"class AssertionError extends Error",
"The error a program throws by hand for a branch that cannot be reached, with an optional message.",
"throw new AssertionError(\"unreachable\");",
),
(
"CloneNotSupportedException",
"Throwables",
"class CloneNotSupportedException extends Exception",
"What `super.clone()` throws for a class that does not implement `Cloneable`; its message is the class's binary name. On a `Cloneable` class `super.clone()` is a field-by-field copy of the same runtime class.",
"try { return (Point) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); }",
),
(
"ArrayStoreException",
"Throwables",
"class ArrayStoreException extends RuntimeException",
"Raised by `System.arraycopy` when an argument is not an array or the two element types cannot be copied between, with the JDK's message (`arraycopy: type mismatch: can not copy int[] into long[]`).",
"try { System.arraycopy(new int[1], 0, new long[1], 0, 1); } catch (ArrayStoreException e) { System.out.println(e); }",
),
(
"IllegalFormatException",
"Throwables",
"class IllegalFormatException extends IllegalArgumentException",
"The base of the `java.util.Formatter` failures. It is not thrown directly; catching it catches the conversion mismatch below.",
"try { String.format(\"%d\", 1.5); } catch (IllegalFormatException e) { System.out.println(\"bad format\"); }",
),
(
"IllegalFormatConversionException",
"Throwables",
"class IllegalFormatConversionException extends IllegalFormatException",
"Raised when a `String.format`/`printf` conversion does not accept its argument's boxed type — `%d` of a `Double`, `%f` of an `Integer`, `%c` of a `String`. The detail message is Java's `<conversion> != <class>`.",
"try { System.out.println(String.format(\"%.2f\", 3)); } catch (IllegalFormatConversionException e) { System.out.println(e.getMessage()); } // f != java.lang.Integer",
),
// ── Functional Interfaces: `prelude.rs` `FUNCTIONAL`. Each is declared to
// javars as an ordinary one-method interface, so a lambda assigned to one
// reaches the same code path a user's own SAM interface does. ──
(
"Runnable",
"Functional Interfaces",
"interface Runnable { void run(); }",
"A no-argument, no-result action. javars runs one thread, so a `Runnable` is only ever invoked directly — there is no `Thread` to hand it to.",
"Runnable r = () -> System.out.println(\"ran\");\nr.run();",
),
(
"Callable",
"Functional Interfaces",
"interface Callable { Object call(); }",
"A no-argument action that produces a result. Java's declares `throws Exception`; javars performs no checked-exception analysis, so the clause is omitted with no behavioural difference.",
"Callable c = () -> 42;\nSystem.out.println(c.call());",
),
(
"Supplier",
"Functional Interfaces",
"interface Supplier { Object get(); }",
"A source of values. The return type is the erasure Java itself uses, which is why a `Supplier` result printed directly renders with the default `ClassName@hash` form rather than through a user `toString()` override — the compiler has no static type to dispatch on.",
"Supplier s = () -> \"made\";\nSystem.out.println(s.get());",
),
(
"Consumer",
"Functional Interfaces",
"interface Consumer { void accept(Object t); default Consumer andThen(Consumer after); }",
"A one-argument action with no result — the type `List.forEach` and `Set.forEach` expect. `andThen` runs both actions on the same argument, in order.",
"Consumer c = x -> System.out.println(x);\nxs.forEach(c);",
),
(
"BiConsumer",
"Functional Interfaces",
"interface BiConsumer { void accept(Object t, Object u); default BiConsumer andThen(BiConsumer after); }",
"A two-argument action with no result — the type `Map.forEach` expects, receiving each key and value. `andThen` runs both actions on the same pair, in order.",
"m.forEach((k, v) -> System.out.println(k + \"=\" + v));",
),
(
"Function",
"Functional Interfaces",
"interface Function { Object apply(Object t); default Function andThen(Function after); default Function compose(Function before); static Function identity(); }",
"A one-argument transformation. `f.andThen(g)` applies `f` first, `f.compose(g)` applies `g` first, and `Function.identity()` returns its argument — the JDK's own bodies, so they compose lambdas without any builtin.",
"Function f = s -> s + \"!\";\nSystem.out.println(f.apply(\"hi\")); // hi!",
),
(
"BiFunction",
"Functional Interfaces",
"interface BiFunction { Object apply(Object t, Object u); default BiFunction andThen(Function after); }",
"A two-argument transformation. `andThen` feeds its result through a one-argument `Function`, which is why that parameter is a `Function` rather than a `BiFunction`.",
"BiFunction add = (a, b) -> a + \"/\" + b;\nSystem.out.println(add.apply(1, 2)); // 1/2",
),
(
"UnaryOperator",
"Functional Interfaces",
"interface UnaryOperator { Object apply(Object t); static UnaryOperator identity(); }",
"A transformation whose argument and result are the same type. Erasure makes its abstract method identical to `Function`'s; the distinct name is what a target type is written as.",
"UnaryOperator u = s -> s + s;\nSystem.out.println(u.apply(\"ab\")); // abab",
),
(
"BinaryOperator",
"Functional Interfaces",
"interface BinaryOperator { Object apply(Object t, Object u); static BinaryOperator minBy(Comparator c); static BinaryOperator maxBy(Comparator c); }",
"A two-argument operator over one type, erased to the same shape as `BiFunction`. `minBy`/`maxBy` turn an ordering into the operator that keeps the smaller/larger of its two arguments.",
"BinaryOperator pick = (a, b) -> a;\nSystem.out.println(pick.apply(\"x\", \"y\")); // x",
),
(
"Predicate",
"Functional Interfaces",
"interface Predicate { boolean test(Object t); default Predicate and(Predicate other); default Predicate negate(); default Predicate or(Predicate other); static Predicate not(Predicate target); static Predicate isEqual(Object targetRef); }",
"A one-argument boolean test. The return type stays primitive rather than erased, so a call participates in javars's numeric typing instead of being an opaque `Object`. `and`/`or` short-circuit exactly as the JDK's bodies do. `isEqual(x)` tests `x.equals(t)`, or `t == null` for a null `x`.",
"Predicate p = s -> s.equals(\"yes\");\nSystem.out.println(p.test(\"yes\")); // true",
),
(
"BiPredicate",
"Functional Interfaces",
"interface BiPredicate { boolean test(Object t, Object u); default BiPredicate and(BiPredicate other); default BiPredicate negate(); default BiPredicate or(BiPredicate other); }",
"A two-argument boolean test, with the same three short-circuiting combinators `Predicate` carries.",
"BiPredicate eq = (a, b) -> a.equals(b);\nSystem.out.println(eq.test(\"a\", \"a\")); // true",
),
(
"Comparator",
"Functional Interfaces",
"interface Comparator { int compare(Object a, Object b); default Comparator reversed(); default Comparator thenComparing(Comparator other); static Comparator naturalOrder(); static Comparator reverseOrder(); static Comparator comparing(Function key); static Comparator comparing(Function key, Comparator keyCmp); static Comparator nullsFirst(Comparator c); static Comparator nullsLast(Comparator c); }",
"An ordering, and the type `List.sort` and the two-argument `Collections.sort` accept. The `int` return is kept rather than erased, because the sort reads its sign. The three statics order elements by their own `compareTo`, which reaches a user `Comparable`'s body through the receiver's runtime class. A sort naming no comparator uses `naturalOrder()`.",
"xs.sort(Comparator.comparing(P::name).reversed());",
),
(
"IntSupplier",
"Functional Interfaces",
"interface IntSupplier { int getAsInt(); }",
"A source of `int` values — the primitive specialization, whose result stays numerically typed.",
"IntSupplier s = () -> 7;\nSystem.out.println(s.getAsInt() + 1); // 8",
),
(
"IntPredicate",
"Functional Interfaces",
"interface IntPredicate { boolean test(int value); default IntPredicate and(IntPredicate other); default IntPredicate negate(); default IntPredicate or(IntPredicate other); }",
"An `int`-argument boolean test, with the primitive-specialized forms of `Predicate`'s three combinators.",
"IntPredicate even = n -> n % 2 == 0;\nSystem.out.println(even.test(4)); // true",
),
(
"IntConsumer",
"Functional Interfaces",
"interface IntConsumer { void accept(int value); default IntConsumer andThen(IntConsumer after); }",
"An `int`-argument action with no result. `andThen` runs both actions on the same value, in order.",
"IntConsumer show = n -> System.out.println(n);\nshow.accept(3);",
),
(
"IntUnaryOperator",
"Functional Interfaces",
"interface IntUnaryOperator { int applyAsInt(int operand); default IntUnaryOperator compose(IntUnaryOperator before); default IntUnaryOperator andThen(IntUnaryOperator after); static IntUnaryOperator identity(); }",
"An `int` to `int` transformation; both sides stay primitive, so the 32-bit wrap applies to arithmetic in the body. Composes in both directions, and `identity()` returns its argument.",
"IntUnaryOperator sq = n -> n * n;\nSystem.out.println(sq.applyAsInt(5)); // 25",
),
(
"IntBinaryOperator",
"Functional Interfaces",
"interface IntBinaryOperator { int applyAsInt(int left, int right); }",
"A two-`int` to `int` transformation.",
"IntBinaryOperator add = (a, b) -> a + b;\nSystem.out.println(add.applyAsInt(2, 3)); // 5",
),
(
"ToIntFunction",
"Functional Interfaces",
"interface ToIntFunction { int applyAsInt(Object value); }",
"A reference-to-`int` transformation, keeping the primitive result type.",
"ToIntFunction len = s -> s.length();\nSystem.out.println(len.applyAsInt(\"abcd\")); // 4",
),
(
"ToDoubleFunction",
"Functional Interfaces",
"interface ToDoubleFunction { double applyAsDouble(Object value); }",
"A reference-to-`double` transformation.",
"ToDoubleFunction half = s -> s.length() / 2.0;\nSystem.out.println(half.applyAsDouble(\"abc\")); // 1.5",
),
(
"ToLongFunction",
"Functional Interfaces",
"interface ToLongFunction { long applyAsLong(Object value); }",
"A reference-to-`long` transformation, the 64-bit sibling of `ToIntFunction`.",
"ToLongFunction big = s -> s.length() * 1000000000L;
System.out.println(big.applyAsLong(\"abc\")); // 3000000000",
),
(
"IntFunction",
"Functional Interfaces",
"interface IntFunction { Object apply(int value); }",
"A primitive-to-reference transformation. Its declared *reference* return type is what converts a `char`-typed body: `IntFunction<Character> f = c -> (char) c; f.apply(97)` is `a`, not 97. `LongFunction` and `DoubleFunction` are the other two widths.",
"IntFunction<Character> ch = c -> (char) c;
System.out.println(ch.apply(97)); // a",
),
(
"IntToLongFunction",
"Functional Interfaces",
"interface IntToLongFunction { long applyAsLong(int value); }",
"A primitive-to-primitive transformation across widths. `IntToDoubleFunction`, `LongToIntFunction` and `DoubleToIntFunction` are the other three javars declares.",
"IntToLongFunction w = i -> i * 3000000000L;
System.out.println(w.applyAsLong(2)); // 6000000000",
),
(
"LongUnaryOperator",
"Functional Interfaces",
"interface LongUnaryOperator { long applyAsLong(long operand); }",
"A same-width transformation at 64 bits, with a `static identity()`. `DoubleUnaryOperator` is the floating one, and `LongBinaryOperator`/`DoubleBinaryOperator` take two operands.",
"LongUnaryOperator dbl = x -> x * 2;
System.out.println(dbl.applyAsLong(3000000000L)); // 6000000000",
),
(
"LongPredicate",
"Functional Interfaces",
"interface LongPredicate { boolean test(long value); }",
"A primitive test, with a `default negate()`. `DoublePredicate` is the floating one; `LongConsumer`/`DoubleConsumer` are the matching void sinks and `LongSupplier`/`DoubleSupplier` the sources.",
"LongPredicate big = x -> x > 1000000000L;
System.out.println(big.test(2000000000L)); // true",
),
// ── Class Members: the members a program declares, and the ones the parser
// and compiler synthesize for it ──
(
"main",
"Class Members",
"public static void main(String[] args) | public static void main(String... args)",
"The entry point. javars scans the compilation unit for a class declaring it and runs that one; a unit with none is rejected before any code is emitted. Both the array and the varargs spelling are accepted.",
"public class Main { public static void main(String[] args) { System.out.println(\"hi\"); } }",
),
(
"args",
"Class Members",
"String[] args",
"`main`'s parameter, bound by a prologue call to the `JARGV` builtin to a fresh array of whatever the CLI collected after the file name. Because it is freshly allocated, mutating it inside `main` cannot affect anything else.",
"System.out.println(args.length);\nfor (String a : args) { System.out.println(a); }",
),
(
"instance field",
"Class Members",
"[modifiers] T name [= initializer];",
"Per-instance state, held in the instance's field map on the host heap. Every field in the class chain is seeded with its type's default when the object is allocated. The *initializers* run later, inside each constructor, at the point JLS 12.5 fixes: after the superclass constructor and before the constructor body. So a field initializer may read an inherited field the superclass constructor just assigned, and a superclass constructor that calls an overridden method sees the subclass's fields at their defaults.",
"class Point { int x; int y = 5; }",
),
(
"constructor",
"Class Members",
"[modifiers] ClassName(params) { … }",
"Initializes a freshly allocated instance, in the three steps JLS 12.5 fixes: the superclass constructor, then this class's field initializers and `{ … }` blocks in textual order, then the body. Constructors overload on parameter type, resolved by the same lowest-assignment-cost rule methods use. A class that declares none gets the implicit no-argument form, whose body is exactly `super()` followed by those initializers. Opening the body with `this(...)` delegates instead, and the delegate runs both steps, so they never run twice.",
"class Point { int x; Point(int x) { this.x = x; } }",
),
(
"implicit super()",
"Class Members",
"class Sub extends Base { /* no declared constructor */ }",
"JLS 8.8.7: a constructor body that does not open with an explicit `this(...)` or `super(...)` runs an implicit `super()` first, and a class that declares no constructor at all gets a default one that does exactly that. Both are emitted, so a parent's constructor body runs whether or not the subclass wrote one, and an intermediate class that declares no constructor still contributes its own `{ … }` blocks at its point in the chain.",
"class Animal { String sound; Animal() { sound = \"generic\"; } }\nclass Dog extends Animal { }\nSystem.out.println(new Dog().sound); // generic",
),
(
"static field",
"Class Members",
"static T name [= initializer];",
"Class-level state, compiled to a chunk global seeded with the type default. Reads resolve through the owning class, so both `C.n` and a bare `n` inside `C` reach the same global.",
"class Counter { static int n = 0; }\nSystem.out.println(Counter.n);",
),
(
"static initializer",
"Class Members",
"static { … }",
"A class-initialization block. Blocks and static field initializers run in textual order, once, when the class is first used — its first `new`, static call, or non-constant static field access — after its superclass has been initialized. The entry class initializes before `main`.",
"class Counter { static int n; static { n = 10; } }",
),
(
"toString",
"Class Members",
"String toString()",
"The rendering used by `println`, `String.valueOf`, and string concatenation. A declared override is dispatched by the compiler *before* the value reaches the host formatter; a class that declares none falls back to `ClassName@hash`, where the hash is the heap handle (deterministic within a run, unlike a JVM identity hash).",
"class Box { public String toString() { return \"Box!\"; } }\nSystem.out.println(new Box()); // Box!",
),
(
"equals",
"Class Members",
"boolean equals(Object other)",
"Derived automatically for a `record` (component-wise, guarded by an `instanceof` test) and for an `enum` (identity, since constants are singletons). A class that declares its own keeps it. The collections do *not* consult an override — their membership tests use value equality for scalars and handle identity for objects.",
"record Point(int x, int y) { }\nSystem.out.println(new Point(1,2).equals(new Point(1,2))); // true",
),
(
"getMessage",
"Class Members",
"String getMessage()",
"The `Throwable` accessor for the detail message, declared once on the root and inherited by every modeled throwable. It returns the field's default — a null reference — when the no-argument constructor was used.",
"catch (NumberFormatException e) { System.out.println(e.getMessage()); }",
),
(
"name",
"Class Members",
"String name()",
"An enum constant's declared name, read from a field the parser synthesizes. A user-declared `name()` wins over the derived one.",
"System.out.println(Color.RED.name()); // RED",
),
(
"ordinal",
"Class Members",
"int ordinal()",
"An enum constant's zero-based declaration position, from a synthesized field.",
"System.out.println(Color.RED.ordinal()); // 0",
),
(
"values",
"Class Members",
"E[] EnumType.values()",
"The static factory returning a fresh array of the enum's constants in declaration order — fresh on every call, exactly as Java hands out a copy so the caller cannot corrupt the enum.",
"System.out.println(Arrays.toString(Color.values())); // [RED, GREEN, BLUE]",
),
(
"valueOf",
"Class Members",
"E EnumType.valueOf(String name)",
"The static lookup by constant name, compiled to a chain of string comparisons. No match raises `IllegalArgumentException` with Java's `No enum constant Type.NAME` message.",
"System.out.println(Color.valueOf(\"BLUE\")); // BLUE",
),
(
"record accessor",
"Class Members",
"T componentName()",
"One derived accessor per record component, named for the component and returning its field. Declaring one by hand suppresses the derived version.",
"record Point(int x, int y) { }\nSystem.out.println(new Point(1, 2).x()); // 1",
),
(
"close",
"Class Members",
"void close()",
"What try-with-resources calls. The parser desugars the resource list into a `finally` that closes each resource in reverse declaration order; there is no `AutoCloseable` interface to implement, so any class declaring `close()` qualifies.",
"class Res { public void close() { System.out.println(\"closed\"); } }\ntry (Res r = new Res()) { } // prints closed",
),
(
"length",
"Class Members",
"int array.length",
"An array's element count — a field read, not a method call, routed through `JFIELD_GET`. Reading it on a null reference raises Java's array-length NullPointerException.",
"int[] a = {1, 2, 3};\nSystem.out.println(a.length); // 3",
),
// ── Method References: the branches of `desugar_method_ref` and
// `type_method_ref`. Every form becomes a lambda with synthesized `#pN`
// parameters, so a reference and its lambda share one code path. ──
(
"Type::new",
"Method References",
"Supplier s = ClassName::new;",
"A constructor reference. For a user class the arity comes from its single declared constructor (or zero when it declares none); a class with two or more constructors is rejected as ambiguous, because javars does not target-type a reference to pick an arity. A modeled stdlib type (`ArrayList`, `HashMap`, `StringBuilder`, `String`, …) takes one parameter: a `Supplier` call leaves it `null` and gets the no-argument constructor, a `Function` call passes its argument to the one-argument constructor.",
"Supplier make = Box::new;\nSystem.out.println(make.get());",
),
(
"Type::instanceMethod",
"Method References",
"Function f = ClassName::method;",
"An unbound instance reference: the synthesized lambda takes the receiver as its first parameter, then the method's own. The name must resolve to exactly one method of the class, otherwise it is rejected rather than guessed.",
"Function area = Sq::area;\nSystem.out.println(area.apply(new Sq()));",
),
(
"Type::staticMethod",
"Method References",
"Function f = ClassName::staticMethod;",
"A reference to a user class's `static` method, with the method's own arity.",
"class Helper { static int twice(int n) { return n * 2; } }\nFunction t = Helper::twice;",
),
(
"Class::stdlibStatic",
"Method References",
"Function f = Integer::parseInt;",
"A reference to a modeled stdlib static. Only the single-arity entries are nameable — among them `Integer.parseInt`, `Long.parseLong`, `Boolean.parseBoolean`, `String.valueOf`, the box `valueOf`s, `Math.sqrt`/`floor`/`ceil`/`round`/`abs`, `Arrays.toString`, `Integer.toBinaryString`/`toHexString`/`toOctalString`, and the two-argument `Math.max`/`min`/`pow`, `Integer::sum`/`max`/`min` and `Double::sum`/`max`/`min`. Names Java overloads on arity (`Integer::toString`) are refused, because a reference has no arity until it is target-typed.",
"Function pi = Integer::parseInt;\nSystem.out.println(pi.apply(\"21\")); // 21",
),
(
"String::instanceMethod",
"Method References",
"Function f = String::toUpperCase;",
"An unbound reference to a `java.lang.String` method, taking the receiver as its first parameter. The no-argument ones (`length`, `isEmpty`, `isBlank`, `strip`/`stripLeading`/`stripTrailing`, `trim`, the case maps, `chars`, `codePoints`, `lines`, `intern`, `hashCode`) and the one-argument ones (`charAt`, `contains`, `startsWith`, `endsWith`, `matches`, `contentEquals`, `equals`, `equalsIgnoreCase`, `concat`, `repeat`, `compareTo`, `compareToIgnoreCase`) are modeled, as is the two-argument `replace`. `substring` and `indexOf` are excluded for the same arity-ambiguity reason.",
"Function up = String::toUpperCase;\nSystem.out.println(up.apply(\"abc\")); // ABC",
),
(
"value::method",
"Method References",
"Supplier s = variable::method; | Supplier s = this::method;",
"A bound reference. The receiver must be a plain name or `this` so the synthesized lambda captures it by value — which is exactly Java's rule that the receiver expression is evaluated once, at the reference.",
"Box b = new Box();\nSupplier bound = b::label;\nSystem.out.println(bound.get());",
),
(
"System.out::println",
"Method References",
"Consumer c = System.out::println; | Consumer c = System.err::print;",
"A reference to a console stream's `print`/`println`. It is special-cased because printing lowers to a builtin rather than to a dispatchable method; any other member name after `System.out::` is refused.",
"Consumer show = System.out::println;\nxs.forEach(show);",
),
(
"Type[]::new",
"Method References",
"IntFunction<T[]> g = Type[]::new;",
"An array constructor reference, `n -> new Type[n]` — the generator `toArray` and `Stream.toArray` take. Any depth works; `String[][]::new` makes the outer dimension with `null` rows.",
"String[] s = Stream.of(\"a\", \"b\").toArray(String[]::new);",
),
(
"Collection::method",
"Method References",
"Function f = List::stream; | Function k = Map.Entry::getKey;",
"An unbound reference to a collection method through a modeled collection type (`List`, `Set`, `Collection`, `Map`, `Map.Entry`, …): `stream`, `size`, `isEmpty`, `getKey`/`getValue`, `contains`, `get`, `put`, and the rest whose arity is the same on every collection. `add` and `remove` are overloaded on arity in `List` and are refused.",
"System.out.println(Stream.of(List.of(1), List.of(2, 3)).flatMap(List::stream).toList());",
),
// ── Format Conversions: `host.rs` `java_format` / `format_conversion` ──
(
"%d",
"Format Conversions",
"String.format(\"%d\", int)",
"Decimal integer. Numeric, so a `0` flag zero-pads it after any leading sign.",
"System.out.println(String.format(\"%d\", 42)); // 42",
),
(
"%f",
"Format Conversions",
"String.format(\"%f\", double)",
"Fixed-point decimal with six fraction digits by default, or as many as `.precision` names.",
"System.out.println(String.format(\"%.2f\", 3.14159)); // 3.14",
),
(
"%s",
"Format Conversions",
"String.format(\"%s\", Object)",
"The argument's Java string form — `true`, `3.0`, `null`, or a class's `toString()` rendering. A `.precision` truncates it to that many characters.",
"System.out.println(String.format(\"%.2s\", \"abcdef\")); // ab",
),
(
"%S",
"Format Conversions",
"String.format(\"%S\", Object)",
"As `%s`, uppercased.",
"System.out.println(String.format(\"%S\", \"abc\")); // ABC",
),
(
"%b",
"Format Conversions",
"String.format(\"%b\", Object)",
"Java's boolean conversion: the value itself for a boolean, `false` for a null reference, and `true` for any other non-null value.",
"System.out.println(String.format(\"%b %b %b\", true, null, \"x\")); // true false true",
),
(
"%B",
"Format Conversions",
"String.format(\"%B\", Object)",
"As `%b`, uppercased.",
"System.out.println(String.format(\"%B\", true)); // TRUE",
),
(
"%x",
"Format Conversions",
"String.format(\"%x\", int)",
"Lowercase hexadecimal. javars formats the value at 64-bit width, so a negative number renders with sixteen digits where Java's `int` conversion gives eight — the one place this conversion diverges.",
"System.out.println(String.format(\"%x\", 255)); // ff",
),
(
"%X",
"Format Conversions",
"String.format(\"%X\", int)",
"Uppercase hexadecimal, with the same 64-bit width note as `%x`.",
"System.out.println(String.format(\"%X\", 255)); // FF",
),
(
"%o",
"Format Conversions",
"String.format(\"%o\", int)",
"Octal.",
"System.out.println(String.format(\"%o\", 8)); // 10",
),
(
"%c",
"Format Conversions",
"String.format(\"%c\", char)",
"The argument's string form. Because javars models a `char` as a one-character string, a genuine char argument renders correctly — but an *integer* code point renders as its digits rather than as the character Java would produce.",
"System.out.println(String.format(\"%c\", 'A')); // A",
),
(
"%%",
"Format Conversions",
"String.format(\"%%\")",
"A literal percent sign; consumes no argument.",
"System.out.println(String.format(\"100%%\")); // 100%",
),
(
"%n",
"Format Conversions",
"String.format(\"%n\")",
"A line separator, always emitted as `\\n` rather than the platform's separator, and consuming no argument.",
"System.out.print(String.format(\"line%n\"));",
),
(
"flag -",
"Format Conversions",
"String.format(\"%-8s\", x)",
"Left-justify within the field width, padding on the right with spaces.",
"System.out.println(String.format(\"[%-6s]\", \"ab\")); // [ab ]",
),
(
"flag 0",
"Format Conversions",
"String.format(\"%08d\", x)",
"Zero-pad to the field width. Applies only to the numeric conversions, and pads after a leading `-` or `+` so the sign stays leftmost.",
"System.out.println(String.format(\"%05.2f\", 3.14159)); // 03.14",
),
(
"flag +",
"Format Conversions",
"String.format(\"%+d\", x)",
"Always show a sign: a `+` on non-negative numbers, with the existing `-` left alone.",
"System.out.println(String.format(\"%+d\", 7)); // +7",
),
(
"width",
"Format Conversions",
"String.format(\"%12s\", x)",
"Minimum field width in characters. A value already at or beyond the width is never truncated by it — only `.precision` shortens.",
"System.out.println(String.format(\"[%8.3f]\", 3.14159)); // [ 3.142]",
),
(
".precision",
"Format Conversions",
"String.format(\"%.3f\", x) | String.format(\"%.2s\", x)",
"Fraction digits for `%f`, or a maximum character count for `%s`/`%S`.",
"System.out.println(String.format(\"%.3f\", 2.0)); // 2.000",
),
(
"ignored flags",
"Format Conversions",
"String.format(\"%,d\", x) | %#x | %(d | % d",
"The grouping, alternate-form, parenthesized-negative, and leading-space flags are accepted and have no effect, so a format string carrying them formats without error but without their decoration. Any conversion character javars does not model is reported as an error rather than rendered wrong.",
"System.out.println(String.format(\"%,d\", 1234)); // 1234 (Java prints 1,234)",
),
// ── Runtime Builtins: the 33 ids `host.rs` registers. Everything with a
// Java-specific meaning that fusevm's own opcodes cannot express lowers
// to one of these; `install` registers 32 and `install_debug` adds
// `DBG_LINE`. The id space is flat, 700 through 732, with no gaps. ──
(
"JPRINTLN",
"Runtime Builtins",
"id 700 · stack [arg?] -> null",
"`System.out.println`. Formats the argument through the Java value-to-string rules and appends a newline — the reason printing is a builtin at all, since fusevm's native print renders shell-style (`true` as `1`, `3.0` as `3`).",
"",
),
(
"JPRINT",
"Runtime Builtins",
"id 701 · stack [arg?] -> null",
"`System.out.print` — as `JPRINTLN` with no trailing newline.",
"",
),
(
"DBG_LINE",
"Runtime Builtins",
"id 702 · stack [] -> null",
"The `--dap` per-statement marker. Registered only by `install_debug` and emitted only by the debug compile path, so a normal run never carries it. It hands control to the DAP server, which pauses in place when the line is a breakpoint or a step target.",
"",
),
(
"JFFI_COMPILE",
"Runtime Builtins",
"id 703 · stack [base64] -> null",
"Compiles an inline `rust { … }` block to a cdylib and registers its exports. The parser desugars the block into a `__rust_compile(\"<base64>\", line)` call, which lowers to this builtin.",
"",
),
(
"JFFI_CALL",
"Runtime Builtins",
"id 704 · stack [args…, name] -> result",
"Calls an FFI export by name. In a program containing a `rust { … }` block, any otherwise-unresolved call becomes one of these; without such a block an unknown name stays a compile-time error.",
"",
),
(
"JSTR_DISPATCH",
"Runtime Builtins",
"id 705 · stack [recv, args…, method] -> result",
"An instance method call on a `String` receiver. It also serves as the fallback for a receiver whose static type the compiler could not pin down: a closure receiver routes to its single abstract method, a collection receiver to the collection methods, and a null receiver to the matching NullPointerException.",
"",
),
(
"JEPRINTLN",
"Runtime Builtins",
"id 706 · stack [arg?] -> null",
"`System.err.println`.",
"",
),
(
"JEPRINT",
"Runtime Builtins",
"id 707 · stack [arg?] -> null",
"`System.err.print`.",
"",
),
(
"JSTATIC_DISPATCH",
"Runtime Builtins",
"id 708 · stack [args…, class, method] -> result",
"A static stdlib call. The collection statics are tried first, because two of them (`Collections.sort` with a comparator) run user code and therefore need the VM; the rest fall through to the pure static table.",
"",
),
(
"JARRAY_NEW",
"Runtime Builtins",
"id 709 · stack [size, default] -> array",
"`new T[n]` — allocates an array filled with the element type's default. A negative size raises `NegativeArraySizeException`.",
"",
),
(
"JARRAY_LIT",
"Runtime Builtins",
"id 710 · stack [e0, …, eN] -> array",
"An array literal: pops the already-evaluated elements deepest-first and pushes a fresh array handle.",
"",
),
(
"JARRAY_GET",
"Runtime Builtins",
"id 711 · stack [array, index] -> element",
"`a[i]`, bounds-checked. The lookup runs inside the heap borrow and any fault is raised after it is released, because raising allocates the throwable on that same heap.",
"",
),
(
"JARRAY_SET",
"Runtime Builtins",
"id 712 · stack [array, index, value] -> value",
"`a[i] = v`, bounds-checked, returning the stored value.",
"",
),
(
"JNEW",
"Runtime Builtins",
"id 713 · stack [className] -> instance",
"`new C(…)` — allocates an instance with an empty field map. The compiler emits the field defaults, the field initializers, and the constructor call immediately after.",
"",
),
(
"JFIELD_GET",
"Runtime Builtins",
"id 714 · stack [recv, name] -> value",
"A field read: an array's `.length` or an instance field. An absent instance field reads as `null`; a null receiver raises the NullPointerException whose wording matches the operation.",
"",
),
(
"JFIELD_SET",
"Runtime Builtins",
"id 715 · stack [recv, name, value] -> value",
"A field write, returning the stored value.",
"",
),
(
"JINSTANCEOF",
"Runtime Builtins",
"id 716 · stack [obj, className] -> boolean",
"`x instanceof C`, resolved by walking the supertype graph the compiler installed before the run.",
"",
),
(
"JCLASSOF",
"Runtime Builtins",
"id 717 · stack [obj] -> className",
"The runtime class name of an instance, which drives the compiler's virtual-dispatch chain. A closure reports the sentinel `#lambda` — not a legal Java identifier, so a user class can never collide with it — and that is the arm routing a functional-interface call to the lambda body.",
"",
),
(
"JARRAY_NEW_MULTI",
"Runtime Builtins",
"id 718 · stack [s0, …, sK, leafDefault] -> array",
"`new T[m][n]…` — builds K+1 nested levels of default-valued arrays. Trailing unsized dimensions (`new int[2][]`) get `null` leaves.",
"",
),
(
"JDIV",
"Runtime Builtins",
"id 719 · stack [a, b] -> double",
"Java's floating-point division. fusevm's native `Div` yields `Undef` for a zero divisor because its shell/awk flavour has no infinities; only the floating path routes here, so statically-integral division keeps the native op and stays JIT-traceable.",
"",
),
(
"JIDIV",
"Runtime Builtins",
"id 745 · stack [a, b] -> long",
"Java's 64-bit integral division. fusevm's native `Div` computes in `f64`, which is exact for two `int` operands but not for a `long`: above 2^53 the operand does not survive the round trip, and `Long.MIN_VALUE / -1` saturates where Java wraps. `int`-width division keeps the native op pair and stays JIT-traceable; only a `long` routes here. A zero divisor is rejected by the compiler's inline check before the call.",
"long q = Long.MAX_VALUE / 2; // 4611686018427387903, not 4611686018427387904",
),
(
"JTHROW",
"Runtime Builtins",
"id 720 · stack [throwable] -> null",
"`throw e` — parks the value as the host's pending exception. The compiler emits the jump to the handler, or the frame exit, immediately after.",
"",
),
(
"JEXC_PENDING",
"Runtime Builtins",
"id 721 · stack [] -> boolean",
"Is an exception in flight? Emitted after every call in a program that uses exceptions — that per-call-site check is how the unwind is modeled, since fusevm has no unwind opcode.",
"",
),
(
"JEXC_TAKE",
"Runtime Builtins",
"id 722 · stack [] -> throwable",
"Claims the pending exception, clearing it. Emitted at the top of a handler.",
"",
),
(
"JEXC_DEPTH",
"Runtime Builtins",
"id 723 · stack [] -> int",
"The current value-stack depth, recorded on entry to a `try`.",
"",
),
(
"JEXC_CUT",
"Runtime Builtins",
"id 724 · stack [depth] -> null",
"Truncates the value stack back to a recorded depth, discarding the operands of the expression the throw abandoned. Without it those operands would pile up once per throw, forever, inside a loop.",
"",
),
(
"JEXC_ABORT",
"Runtime Builtins",
"id 725 · stack [] -> null",
"Reports an exception that reached the top of `main` in Java's own `Exception in thread \"main\" <class>: <message>` form and halts, so the process exits non-zero the way `java` does.",
"",
),
(
"JFAULT",
"Runtime Builtins",
"id 726 · stack [className, message] -> null",
"Raises a fault the compiler detected inline — integral division by zero, and an enum `valueOf` with no matching constant — through the same path a host-detected fault takes, so the throwable is catchable.",
"",
),
(
"JARGV",
"Runtime Builtins",
"id 727 · stack [] -> array",
"`main`'s `String[] args`, as a fresh array of the program arguments the CLI collected. Called once by the prologue, so the array the program sees is its own.",
"",
),
(
"JMAKE_CLOSURE",
"Runtime Builtins",
"id 728 · stack [caps…, nameIdx, params, ncap] -> closure",
"Builds a lambda closure, snapshotting the enclosing locals by value. A javars local lives in a call-frame slot that does not outlive the frame, so a by-value snapshot is the only model that also gives the enhanced `for` its per-iteration capture.",
"",
),
(
"JCLOSURE_CALL",
"Runtime Builtins",
"id 729 · stack [closure, args…] -> result",
"Invokes a closure in its own fusevm call frame through a nested run. A mismatched arity is padded with `null` or truncated rather than corrupting the frame, and an exception already in flight suppresses the call so a unwinding frame cannot re-run side effects.",
"",
),
(
"JCOLL_NEW",
"Runtime Builtins",
"id 730 · stack [kindName, seed] -> collection",
"Allocates a modeled `java.util` collection, optionally seeded by a copy constructor's argument. Collections live on the same heap slab as arrays and instances, so aliasing, `==` identity, and passing one to a method all behave like Java references with no extra machinery.",
"",
),
(
"JCOLL_DISPATCH",
"Runtime Builtins",
"id 731 · stack [recv, args…, method] -> result",
"An instance method on a collection receiver. Methods that run user code (`sort` with a comparator, `forEach`) snapshot the elements and re-enter the VM with no heap borrow held, because a lambda body can allocate.",
"",
),
(
"JITER_ARRAY",
"Runtime Builtins",
"id 732 · stack [iterable] -> array",
"The elements of an enhanced-`for` iterable, as an array. An array receiver is handed back unchanged so an array loop keeps aliasing; a collection is snapshotted, which the loop then reads through `JITER_HAS`/`JITER_GET` — live for a `List`, with the modification check a Java iterator makes. Emitted only when the compiler could not prove the iterable is already an array.",
"",
),
(
"Stream.iterate",
"Streams",
"Stream.iterate(seed, next) | Stream.iterate(seed, hasNext, next)",
"The seed, then `next` applied to the previous element. The two-argument form is unbounded: it is pulled one element at a time by the terminal, so `next` runs only as often as an element is demanded and a `limit` or short-circuiting terminal ends it. `IntStream`/`LongStream`/`DoubleStream.iterate` are the same on their shape.",
"System.out.println(Stream.iterate(1, x -> x * 2).limit(5).toList()); // [1, 2, 4, 8, 16]",
),
(
"Stream.generate",
"Streams",
"Stream.generate(supplier)",
"An unbounded stream of the supplier's answers, called once per element pulled.",
"int[] n = {0};\\nSystem.out.println(Stream.generate(() -> n[0]++).limit(3).toList()); // [0, 1, 2]",
),
(
"Stream.concat",
"Streams",
"Stream.concat(a, b) | IntStream.concat(a, b)",
"The elements of `a`, then of `b`, each part driven only as far as the downstream pipeline wants. `Stream.empty()` and `Stream.ofNullable(x)` are the zero- and one-element sources.",
"System.out.println(Stream.concat(Stream.of(1), Stream.of(2, 3)).toList()); // [1, 2, 3]",
),
(
"takeWhile",
"Streams",
"Stream<T> takeWhile(p) | Stream<T> dropWhile(p)",
"`takeWhile` passes elements while `p` accepts them and ends the pipeline at the first it rejects; `dropWhile` drops that prefix and passes everything after it.",
"System.out.println(Stream.of(1, 2, 5, 1).takeWhile(x -> x < 3).toList()); // [1, 2]",
),
(
"mapMulti",
"Streams",
"Stream<R> mapMulti(BiConsumer<T, Consumer<R>> mapper)",
"Each element is handed to `mapper` with a `Consumer`; everything the mapper accepts goes downstream in order, in place of the element — the JDK's own default body, a `flatMap` over a buffer.",
"System.out.println(Stream.of(1, 2).<Object>mapMulti((v, sink) -> { sink.accept(v); sink.accept(-v); }).toList()); // [1, -1, 2, -2]",
),
(
"flatMapToInt",
"Streams",
"IntStream flatMapToInt(f) | LongStream flatMapToLong(f) | DoubleStream flatMapToDouble(f)",
"`flatMap` into a primitive stream: the elements of each stream `f` answers go on in place of the element, and the pipeline takes the primitive shape, so `sum()` and `max()` answer as that stream's do.",
"System.out.println(Stream.of(\"ab\", \"c\").flatMapToInt(String::chars).sum()); // 294",
),
(
"summaryStatistics",
"Streams",
"IntSummaryStatistics summaryStatistics() | Collectors.summarizingInt/Long/Double(mapper) | new IntSummaryStatistics()",
"Count, sum, min, max and average in one pass, as the JDK's `Int`/`Long`/`DoubleSummaryStatistics`: `getCount`, `getSum`, `getMin`, `getMax`, `getAverage`, `accept`, `combine`, and the JDK's `toString` (`IntSummaryStatistics{count=…, sum=…, min=…, average=…, max=…}`). An empty one's extremes are the type's `MAX_VALUE`/`MIN_VALUE` (the infinities for `double`); the `double` sum is the compensated one.",
"System.out.println(IntStream.of(3, 1, 2).summaryStatistics().getMax()); // 3",
),
(
"Collectors.toMap",
"Streams",
"toMap(key, value) | toMap(key, value, merge) | toMap(key, value, merge, mapFactory)",
"A map from each element's key to its value. Without a merge function a repeated key is `IllegalStateException: Duplicate key k (attempted merging values a and b)`; with one, the values are folded by `Map.merge`. The fourth argument supplies the map, so `TreeMap::new` sorts it.",
"System.out.println(Stream.of(\"a\", \"bb\", \"cc\").collect(Collectors.toMap(String::length, s -> s, (x, y) -> x + y))); // {1=a, 2=bbcc}",
),
(
"Collectors.groupingBy",
"Streams",
"groupingBy(key) | groupingBy(key, downstream) | groupingBy(key, mapFactory, downstream)",
"Groups in encounter order, each reduced by the downstream collector (`toList` when none is named). The downstream may be any collector: `counting`, `mapping`, `summingInt`, `averagingDouble`, `minBy`/`maxBy`, `reducing`, `toCollection`, `collectingAndThen`, `teeing`, or another `groupingBy`.",
"System.out.println(Stream.of(\"x\", \"yy\", \"zz\").collect(Collectors.groupingBy(String::length, Collectors.counting()))); // {1=1, 2=2}",
),
(
"Collectors.partitioningBy",
"Streams",
"partitioningBy(predicate) | partitioningBy(predicate, downstream)",
"Always both keys, `false` first, each reduced by the downstream collector.",
"System.out.println(Stream.of(1, 2, 3, 4).collect(Collectors.partitioningBy(x -> x > 2))); // {false=[1, 2], true=[3, 4]}",
),
];
/// The corpus, exposed for the LSP providers and for offline doc generation.
pub fn corpus() -> &'static [Entry] {
REFERENCE
}