Every name the current javars build implements — reserved and contextual keywords, literal forms, declaration types, operators, console IO, the java.lang.String and java.util method surfaces, the static library, the modeled throwables and functional interfaces, synthesized class members, method-reference forms, String.format conversions, and the runtime builtin id space. Each entry carries its signature, a description written from the implementation, and — where one clarifies the behaviour — a runnable example. Where javars computes something other than java does, the entry says so. This page is generated from the reference corpus (src/reference.rs) by the gen-docs binary, and the language server reads the same table, so the page, the editor tooling, and the runtime cannot drift apart.
Contextual Keywords
# package
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
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
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
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
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) { }
// new Point(1, 2) prints as Point[x=1, y=2]
# extends
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
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
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(); }
class Impl extends Base { String tag() { return "impl"; } }
# final
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;
for (final String s : names) { System.out.println(s); }
# private
private <member>
Parsed and dropped, like every access modifier. javars enforces no visibility.
class Box { private int n; private int get() { return n; } }
# protected
protected <member>
Parsed and dropped, like every access modifier.
class Base { protected String tag() { return "base"; } }
# synchronized
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"); }
Object lock = new Object();
synchronized (lock) { System.out.println("critical"); }
# native
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
volatile <field>
Accepted as a field modifier and dropped — single-threaded execution gives it nothing to order.
class Flag { volatile boolean set; }
# transient
transient <field>
Accepted as a field modifier and dropped. javars has no serialization.
class Cache { transient int hits; }
# throws
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
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
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
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
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
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
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
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
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
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;
assert (x = 5) > 0;
System.out.println(x); // 0
# null
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;
System.out.println(s + " " + (s == null)); // null true
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
System.out.println("n=" + 3.0); // n=3.0
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
a * b
Multiplication, wrapping at 32 bits when both operands are statically int-width.
System.out.println(6 * 7); // 42
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
System.out.println(7.0 / 0.0); // Infinity
a % b
Remainder, taking the sign of the dividend exactly as Java does.
System.out.println(-7 % 3); // -1
# unary -
-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 +
+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';
System.out.println("" + +c); // 65
System.out.println("" + c); // A
!a
Logical negation, lowered to Op::LogNot.
if (!done) { System.out.println("still going"); }
# ==
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)
# !=
a != b
Inequality — the exact negation of ==, including its string behaviour.
if (n != 0) { System.out.println(100 / n); }
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); }
a > b
Greater-than, with the same numeric-or-lexicographic behaviour as <.
if (score > best) { best = score; }
# <=
a <= b
Less-than-or-equal.
for (int i = 1; i <= 10; i++) { }
# >=
a >= b
Greater-than-or-equal.
if (n >= 0) { System.out.println("non-negative"); }
# &&
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); }
# ||
a || b
Short-circuiting disjunction, the mirror of && via Op::JumpIfTrueKeep.
if (n < 0 || n > 100) { System.out.println("out of range"); }
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;
n = 5;
arr[0] = n;
# +=
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
String s = "a"; s += "b"; // "ab"
# -=
target -= expr;
Compound subtraction, with the same int narrowing on store.
int i = 5; i -= 2; // 3
# *=
target *= expr;
Compound multiplication.
int i = 5; i *= 2; // 10
# /=
target /= expr;
Compound division, following the same integral-versus-floating split as /.
int i = 10; i /= 2; // 5
# %=
target %= expr;
Compound remainder.
int i = 10; i %= 4; // 2
# ++
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++) { }
int v = 5; System.out.println(v++ + "," + v); // 5,6
int w = 5; System.out.println(++w + "," + w); // 6,6
int[] a = {1}; System.out.println(a[0]++ + "," + a[0]); // 1,2
# --
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
int m = 3; System.out.println(--m); // 2
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
System.out.println(true & false); // false
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
System.out.println(true | false); // true
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
System.out.println(true ^ true); // false
~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
# <<
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
System.out.println(1 << 33); // 2
System.out.println(1L << 40); // 1099511627776
# >>
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
# >>>
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
System.out.println(-8L >>> 1); // 9223372036854775804
# &= |= ^= <<= >>= >>>=
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;
System.out.println(v); // 11
# (type) expr
(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
System.out.println((byte) 200); // -56
System.out.println((char) 65); // A
System.out.println((double) 7 / 2); // 3.5
# ?:
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";
# ->
(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 + "!";
System.out.println(up.apply("hi")); // hi!
# ::
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;
# []
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};
System.out.println(a[1]); // 2
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);
System.out.println(arr.length);
# ()
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));
Static Library
# AtomicInteger
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();
List.of(1, 2).forEach(x -> n.addAndGet(x));
System.out.println(n); // 3
# StringJoiner
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
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();
b.set(1, 4);
System.out.println(b); // {1, 2, 3}
# BigInteger
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;
for (int i = 2; i <= 25; i++) f = f.multiply(BigInteger.valueOf(i));
System.out.println(f); // 15511210043330985984000000
# BigDecimal
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));
System.out.println(p.setScale(1, RoundingMode.HALF_UP)); // 60.0
# MathContext
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);
System.out.println(new BigDecimal("1.23456789").round(mc)); // 1.2345
# RoundingMode
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
# Pattern
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
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 (with a replacement string or a Function<MatchResult, String> whose answer is expanded per match), appendReplacement/appendTail, results() and toMatchResult() are supported; with no current match the accessors throw IllegalStateException: No match found.
Matcher m = p.matcher("bob@site");
while (m.find()) System.out.println(m.group(2));
# StrictMath
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
double Math.random()
A uniform double in [0, 1), from one unseeded Random created on first use.
double d = Math.random();
# Math.abs
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
String Integer.toString(int i)
The decimal rendering of an integer.
System.out.println(Integer.toString(255)); // 255
# Integer.toString
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
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
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
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
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
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();
for (int i = 0; i < 3; i++) { b.append(i).append(','); }
System.out.println(b); // 0,1,2,
# String.format
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
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
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}};
Arrays.sort(g, (x, y) -> x[0] - y[0]);
System.out.println(Arrays.deepToString(g)); // [[2, 2], [3, 1]]
# Integer.decode
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
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
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
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};
Arrays.parallelPrefix(p, Integer::sum);
System.out.println(Arrays.toString(p)); // [1, 3, 6, 10]
# Integer.parseUnsignedInt
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
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
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
boolean Character.isDigit(char c) | isLetter | isLetterOrDigit | isAlphabetic | isSpaceChar | isISOControl | isWhitespace | isUpperCase | isLowerCase | isTitleCase
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 Statics
# List.copyOf
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
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
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
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}
# Collections.addAll
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);
# Arrays.asList
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);
xs.set(0, 9); // fine
// xs.add(4); // UnsupportedOperationException
# List.of
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
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
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
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
void Collections.reverse(List<T> list)
Reverses the list in place.
Collections.reverse(xs);
# EnumSet
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
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
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
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
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
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
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
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
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
void Collections.fill(List<? super T> list, T obj)
Sets every position to obj.
Collections.fill(xs, 0);
# Collections.indexOfSubList
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
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
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
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
# size
int size()
The number of elements.
System.out.println(xs.size());
# isEmpty
boolean isEmpty()
True when the list holds no elements.
if (xs.isEmpty()) { System.out.println("none"); }
# add
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
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
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
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
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
xs.remove(Integer.valueOf(20)); // by value
# subList
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));
List<Integer> v = l.subList(1, 3);
v.set(0, 99);
System.out.println(l); // [10, 99, 30, 40]
# clear
void clear()
Removes every element. Structural, so it is refused on a fixed-size or immutable list.
xs.clear();
# contains
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
int indexOf(Object o)
The index of the first matching element, or -1.
System.out.println(xs.indexOf("a"));
# lastIndexOf
int lastIndexOf(Object o)
The index of the last matching element, or -1.
System.out.println(xs.lastIndexOf("a"));
# addAll
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
boolean equals(Object other)
Element-wise equality against another sequence of the same length.
System.out.println(xs.equals(ys));
# sort
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Throwables
# Throwable
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
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
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
class RuntimeException extends Exception
The unchecked branch, and the superclass of every fault the runtime raises.
throw new RuntimeException("boom");
# IllegalArgumentException
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
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
class IllegalStateException extends RuntimeException
Never raised by the runtime; supplied so program code can throw and catch it.
throw new IllegalStateException("bad state");
# ArithmeticException
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
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;
// s.length(); // Cannot invoke "String.length()" because the receiver is null
# ClassCastException
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
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);
try { xs.add(3); } catch (UnsupportedOperationException e) { System.out.println("[" + e.getMessage() + "]"); } // []
# NegativeArraySizeException
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
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
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];
try { System.out.println(a[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); }
# StringIndexOutOfBoundsException
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
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));
List<Integer> v = l.subList(0, 2);
l.add(4);
// v.get(0); // ConcurrentModificationException
# NoSuchElementException
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
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
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
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
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
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
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
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
# Runnable
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");
r.run();
# Callable
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;
System.out.println(c.call());
# Supplier
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";
System.out.println(s.get());
# Consumer
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);
xs.forEach(c);
# BiConsumer
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
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 + "!";
System.out.println(f.apply("hi")); // hi!
# BiFunction
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;
System.out.println(add.apply(1, 2)); // 1/2
# UnaryOperator
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;
System.out.println(u.apply("ab")); // abab
# BinaryOperator
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;
System.out.println(pick.apply("x", "y")); // x
# Predicate
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");
System.out.println(p.test("yes")); // true
# BiPredicate
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);
System.out.println(eq.test("a", "a")); // true
# Comparator
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
interface IntSupplier { int getAsInt(); }
A source of int values — the primitive specialization, whose result stays numerically typed.
IntSupplier s = () -> 7;
System.out.println(s.getAsInt() + 1); // 8
# IntPredicate
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;
System.out.println(even.test(4)); // true
# IntConsumer
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);
show.accept(3);
# IntUnaryOperator
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;
System.out.println(sq.applyAsInt(5)); // 25
# IntBinaryOperator
interface IntBinaryOperator { int applyAsInt(int left, int right); }
A two-int to int transformation.
IntBinaryOperator add = (a, b) -> a + b;
System.out.println(add.applyAsInt(2, 3)); // 5
# ToIntFunction
interface ToIntFunction { int applyAsInt(Object value); }
A reference-to-int transformation, keeping the primitive result type.
ToIntFunction len = s -> s.length();
System.out.println(len.applyAsInt("abcd")); // 4
# ToDoubleFunction
interface ToDoubleFunction { double applyAsDouble(Object value); }
A reference-to-double transformation.
ToDoubleFunction half = s -> s.length() / 2.0;
System.out.println(half.applyAsDouble("abc")); // 1.5
# ToLongFunction
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
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
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
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
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
Runtime Builtins
# JPRINTLN
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
id 701 · stack [arg?] -> null
System.out.print — as JPRINTLN with no trailing newline.
# DBG_LINE
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
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
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
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
id 706 · stack [arg?] -> null
System.err.println.
# JEPRINT
id 707 · stack [arg?] -> null
System.err.print.
# JSTATIC_DISPATCH
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
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
id 710 · stack [e0, …, eN] -> array
An array literal: pops the already-evaluated elements deepest-first and pushes a fresh array handle.
# JARRAY_GET
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
id 712 · stack [array, index, value] -> value
a[i] = v, bounds-checked, returning the stored value.
# JNEW
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
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
id 715 · stack [recv, name, value] -> value
A field write, returning the stored value.
# JINSTANCEOF
id 716 · stack [obj, className] -> boolean
x instanceof C, resolved by walking the supertype graph the compiler installed before the run.
# JCLASSOF
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
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
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
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
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
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
id 722 · stack [] -> throwable
Claims the pending exception, clearing it. Emitted at the top of a handler.
# JEXC_DEPTH
id 723 · stack [] -> int
The current value-stack depth, recorded on entry to a try.
# JEXC_CUT
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
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
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
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
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
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
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
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
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.