var and Text Blocks

Local Variable Type Inference (Java 10)

var lets the compiler infer the type of a local variable from its initializer. The variable is still statically typed — var is not JavaScript's var.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        var count = 10;                                    // int
        var name = "Careeroza";                            // String
        var scores = new HashMap<String, List<Integer>>(); // HashMap<String, List<Integer>>
        scores.put("java", List.of(80, 92));

        for (var entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        System.out.println(name.length() + count);
        // count = "ten";   // compile error: count is an int
    }
}

Output

java -> [80, 92]
19
AllowedNot allowed
local variables with an initializer, for/for-each, try-with-resources, lambda params (Java 11)fields, method parameters, return types, var x; without initializer, var x = null;

Tip: Use var when the type is obvious from the right side (var list = new ArrayList<Order>()). Avoid it when it hides meaning (var result = service.process()).

Text Blocks (Java 15)

A text block is a multi-line string between """ markers. No more + and escaped quotes for JSON, SQL or HTML. Common leading indentation is removed automatically.

Example

public class Main {
    public static void main(String[] args) {
        String sql = """
                SELECT id, name, price
                FROM products
                WHERE category = ? AND price < ?
                ORDER BY price""";

        String json = """
                {
                  "orderId": "%s",
                  "amount": %d,
                  "status": "PLACED"
                }
                """.formatted("ORD-77", 1499);

        System.out.println(sql);
        System.out.println(json);
    }
}

Output

SELECT id, name, price
FROM products
WHERE category = ? AND price < ?
ORDER BY price
{
  "orderId": "ORD-77",
  "amount": 1499,
  "status": "PLACED"
}