What are var (local variable type inference) and text blocks, and what are their limitations?
Quick Answer
var (Java 10+) lets the compiler infer a local variable's type from its initializer, reducing boilerplate for verbose generic types, but it's purely a compile-time convenience — the variable is still statically typed, just written implicitly, and var can't be used for fields, method parameters/returns, or without an initializer. Text blocks (Java 15+, """) let you write multi-line string literals without escape-heavy concatenation, automatically handling indentation stripping, but still require explicit escapes for things like trailing significant whitespace.
Detailed Answer
var (Java 10+) lets you omit an explicit type for a local variable, letting the compiler infer it from the initializer expression:
var list = new ArrayList<Map<String, List<Integer>>>(); // vs. spelling the type twice
var name = "Alice"; // still statically typed as String — var is not dynamic typing
Limitations:
- Only for local variables with an initializer — not for fields, method parameters, or return types.
- Requires an initializer (
var x;alone doesn't compile — there's nothing to infer from). - Can't be initialized to
nulldirectly (var x = null;doesn't compile — no type to infer). - It's purely syntactic — the compiled bytecode is identical to writing the explicit type;
varcarries no runtime behavior difference and the variable remains fully statically typed. - Overuse can hurt readability when the inferred type isn't obvious from the right-hand side (e.g.,
var result = process(x);hides what typeresultactually is without IDE assistance).
Text blocks (finalized in Java 15, triple-double-quote delimiters) let you write multi-line string literals without escaping every newline/quote or concatenating with +:
String json = """
{
"name": "Alice",
"age": 30
}
""";
Text blocks automatically strip a common leading-whitespace margin (based on the closing delimiter's position) and normalize line terminators, making embedded JSON/SQL/HTML far more readable than an escaped one-liner. Limitations: you still need an escaped delimiter to include a literal triple-quote, a trailing backslash to suppress an unwanted trailing newline, and trailing whitespace on a line is stripped by default unless explicitly preserved with \s or \ escapes — a common surprise when trailing spaces are semantically significant.