Some Interesting String Features in Java

1. String Literals: Constants and Singletons

In Java, if the same string literal (e.g., "Hello World") is used in multiple variable declarations, the Java Virtual Machine (JVM) may create only one instance in memory. Thus, string literals act as constants or singletons.

constants or singleton

In this case, both str1 and str2 point to the same String object stored in the String Pool of the JVM.

String str1 = "Hello World";
String str2 = "Hello World";

JVM maintains a String Constant Pool, where all string literals are stored. Even if classes from different projects are compiled separately, they may still share the same constant String objects at runtime.

Separate String Objects

If you want two String variables to point to separate objects, use the new operator.

Although both strings contain the same text, the JVM creates two different objects in memory.

String str1 = new String("Hello World");
String str2 = new String("Hello World");

2. Compact Strings

Introduced in Java 9, Compact Strings optimize memory usage for String objects.

Before Java 9 (UTF-16 representation)

After Java 9 (Compact Strings enabled)

3. Java Text Blocks

Introduced in Java 13 (as a preview) and officially released in Java 15, Text Blocks provide a more readable and convenient way to define multi-line strings in Java. This feature eliminates the need for escape sequences (\n, ", etc.) and improves code maintainability.

A text block is a multi-line string literal enclosed within triple double-quotes (“””). It automatically preserves new lines and indentation, making it an ideal choice for defining formatted text such as:

Features and Advantages

Text blocks preserve new lines as they appear in the source code.

String message = """
    Hello,
    This is a multi-line message.
    Have a great day!
    """;
System.out.println(message);
Hello,
This is a multi-line message.
Have a great day!

In regular Java strings, double quotes inside the string must be escaped (\"). With text blocks, escaping is unnecessary.

String json = """
    {
        "name": "Alice",
        "age": 25
    }
    """;
System.out.println(json);
{
    "name": "Alice",
    "age": 25
}

By default, Java removes common leading whitespace based on the leftmost non-space character.

String sqlQuery = """
        SELECT * FROM users
        WHERE active = true
        ORDER BY created_at DESC;
    """;

The leading whitespace in each line is automatically aligned.

Although escaping quotes (") is not required, certain characters still need escaping such as Triple double-quotes (""") and Backslashes (\).

String text = """
    This is a "quote" inside a text block.
    To use triple quotes, escape one: \"""
    This is how you add \"\\\" inside text blocks.
    """;
System.out.println(text);
This is a "quote" inside a text block.
To use triple quotes, escape one: """
This is how you add "\"" inside text blocks.

Text blocks support String formatting using .formatted().

String template = """
    Name: %s
    Age: %d
    Country: %s
    """.formatted("Alice", 25, "Canada");

System.out.println(template);
Name: Alice
Age: 25
Country: Canada

Use Cases of Java Text Blocks

String sql = """
    SELECT id, name, email
    FROM users
    WHERE status = 'active'
    ORDER BY created_at DESC;
    """;
String html = """
    <html>
        <head>
            <title>Java Text Blocks</title>
        </head>
        <body>
            <h1>Welcome to Java 15!</h1>
        </body>
    </html>
    """;

Summary

Feature Description Available Since
String Literals Identical string literals are stored in the String Pool, preventing redundant object creation. All Versions
String Singleton String literals with the same value share the same instance, unless explicitly created with new String(). All Versions
Compact Strings If a String contains only Latin-1 characters, it is stored using byte[] to reduce memory usage. Java 9+
Text Blocks Multi-line strings with automatic formatting and built-in support for quotes. Java 13+