Special Characters and Text Blocks

Escapes Inside Strings

Example

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\": \"Asha\", \"city\": \"Pune\"}";
        System.out.println(json);
        System.out.println("Col1\tCol2\nA\tB");
        System.out.println("Windows path: D:\\projects\\app");
    }
}

Output

{"name": "Asha", "city": "Pune"}
Col1	Col2
A	B
Windows path: D:\projects\app

Text Blocks (Java 15+)

Example

A text block starts and ends with three double quotes. It keeps line breaks and lets you write quotes without escaping. Perfect for JSON, SQL and HTML.

public class Main {
    public static void main(String[] args) {
        String sql = """
            SELECT name, price
            FROM products
            WHERE price < 500
            ORDER BY price""";
        System.out.println(sql);

        String json = """
            {"id": 101, "name": "Laptop Bag"}
            """;
        System.out.print(json);
    }
}

Output

SELECT name, price
FROM products
WHERE price < 500
ORDER BY price
{"id": 101, "name": "Laptop Bag"}

Note: The common leading indentation is removed automatically. Content starts on the line after the opening """.