Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaText Blocks in Java 15

Text Blocks in Java 15

In this article, we are going to discuss the Java 15 text blocks feature to declare multi-line strings most efficiently. We all know that how we can declare multi-line strings and that too quite easily with the help of concatenation, string’s join method, StringBuilder append method, etc. Now the question will arise in our mind that if everything is this simple then what is the need for a new feature i.e. text blocks to declare multi-line strings. So let’s first try to understand the problem and then we will understand the need for a text block.

In earlier releases of the JDK, embedding multi-line code snippets required a tangled mess of explicit line terminators, string concatenations, and delimiters. Text blocks eliminate most of these obstructions, allowing you to embed code snippets and text sequences more or less as-is.

A text block is an alternative form of Java string representation that can be used anywhere a traditional double-quoted string literal can be used. Text blocks begin with a “”” (3 double-quote marks) observed through non-obligatory whitespaces and a newline. For example:

Java




// Using a literal string
String text1 = "Geeks For Geeks";
  
// Using a text block
String text2 = """
                Geeks For Geeks""";


Note: Since Java 15, text blocks are available as a standard feature. With Java 13 and 14, we needed to enable it as a preview feature.

The object created from text blocks is java.lang.String with the same properties as a regular string enclosed in double quotes. This includes the presentation of objects and the interning. Continue with text1 and text2 from the previous examples,

Java




// Both text1 and text2 are strings of equal value
text1.equals(text2)    // true
  
// Both text1 and text2 intern to the same string
text1 == text2         // true


Text blocks may be utilized in the region of a string literal to enhance the clarity and readability of the code. This typically takes place whilst a string literal is used to symbolize a multi-line string. In this example there’s a substantial muddle from citation marks, newline escapes, and concatenation operators:

Java




// ORIGINAL
String message = "A-143, 9th Floor, Sovereign Corporate Tower,\n" +
      "Sector-136, Noida,\n" +
      "Uttar Pradesh - 201305";
  
// BETTER : Using text blocks 
// gets rid of lots of the clutter
String message = """
    A-143, 9th Floor, Sovereign Corporate Tower,
    Sector-136, Noida,
    Uttar Pradesh - 201305""";


In this article, we checked out the Java Text Blocks feature. As part of learning, we can learn more about text blocks i.e. Indentation, Escaping, etc. It might not be a game-changer, however, it enables us to write more readable code, which is generally a good thing.

RELATED ARTICLES

Most Popular

Recent Comments