• 🌟 Java Text Blocks

    with French Literary Flair

    A text block in Java offers a clean and elegant way to write multi-line strings. Its main purpose is to increase clarity and reduce boilerplate when expressing longer string content, such as quotes, documentation, or even HTML or SQL snippets.

    Before Java introduced text blocks, crafting a multi-line string meant dealing with messy concatenations and newline escape characters (\n), making code harder to read and maintain. With text blocks, the code becomes more concise, readable, and true to the original formatting.

    📖 Traditional String vs. Text Block

    Let’s consider a simple example using the name of a famous French author:

    // Using a traditional string
    String dqName = "Victor Hugo";
    
    // Using a text block
    String tbName = """
                    Victor Hugo""";

    Both variables contain the same string and behave identically:

    dqName.equals(tbName); // true
    dqName == tbName;      // true (both refer to the same interned String)
    

    ✍️ Mixing Text Blocks and Literals

    You can mix text blocks with standard string literals in expressions:

    String intro = "Un grand écrivain :";
    String quote = """
                   Victor Hugo""";
    String message = intro + " " + quote + ".";

    📬 Passing a Text Block as a Method Argument

    Here’s an example using a beautiful quote from Antoine de Saint-Exupéry’s Le Petit Prince:

    System.out.println("""
        "On ne voit bien qu’avec le cœur.
        L’essentiel est invisible pour les yeux."
        – Antoine de Saint-Exupéry
        """);

    🔍 Using String Methods on a Text Block

    You can treat a text block like any other string:

    """
    Albert Camus""".substring(7).equals("Camus"); // true
    

    🧹 Cleaning Up a Multi-Line Quote

    Let’s take a look at a quote from Voltaire written the old way:

    // OLD WAY (messy)
    String quote = "\"Il faut cultiver notre jardin,\" dit Candide.\n" +
                   "\"C’est le seul moyen de rendre la vie supportable.\"\n";

    Now, rewritten with a text block:

    // MODERN WAY (clean and clear)
    String quote = """
        "Il faut cultiver notre jardin," dit Candide.
        "C’est le seul moyen de rendre la vie supportable."
        """;

    🏛️ Final Example: A Victor Hugo Masterpiece

    String lesMiserables = """
        "Il n’y a ni mauvaises herbes ni mauvais hommes.
        Il n’y a que de mauvais cultivateurs."
        – Victor Hugo
        """;
    System.out.println(lesMiserables);

    ✅ Conclusion

    Text blocks are ideal when working with:

    🟣 Long literary quotes 📜

    🟣 Multiline documentation 🧾

    🟣 Embedded code snippets 💻

    🟣 Clean string formatting 🎨

    They help preserve intent, reduce clutter, and improve readability, especially when you're inspired by the beauty of language — just like our greatest French writers.