Java Text Blocks Example

1. Introduction

Java Text Blocks simplify the declaration of multiline string literals. They start and end with three double quotes (""") and automatically format the string in a more readable and manageable way, preserving the intended line breaks and white spaces without the need for escape sequences.

2. Example Steps

1. Define multiline strings using Text Blocks.

2. Use Text Blocks in JSON formatting and SQL queries.

3. Manipulate and process Text Block content.

3. Code Program

public class TextBlockExample {
    public static void main(String[] args) {
        // JSON String using Text Block
        String json = """
            {
                "name": "Alice",
                "age": 30,
                "city": "Wonderland"
            }
            """;

        // SQL query using Text Block
        String query = """
            SELECT name, age, city
            FROM users
            WHERE city = 'Wonderland'
            ORDER BY name
            """;

        System.out.println("JSON Example:\n" + json);
        System.out.println("SQL Query Example:\n" + query);
    }
}

Output:

JSON Example:
{
    "name": "Alice",
    "age": 30,
    "city": "Wonderland"
}
SQL Query Example:
SELECT name, age, city
FROM users
WHERE city = 'Wonderland'
ORDER BY name

Explanation:

1. The json variable demonstrates a Text Block representing a JSON string. The natural multiline layout makes it more readable and maintainable.

2. The query variable uses a Text Block to define a multiline SQL query, enhancing readability and reducing the risk of syntax errors often caused by line concatenation and escape characters.

3. The System.out.println statements output the Text Block contents, clearly showing the preserved formatting and structure.

4. These examples illustrate the effectiveness of Text Blocks in handling complex, multiline strings in real-world programming scenarios like JSON handling and database querying.


Comments