javatextblockjava-13preview-feature

JDK 13 preview feature :Textblock returns false for equals and == .Is the tab spaces dependent?


equals and == return false for a text block string, though they print the same in the console.

public class Example {
    public static void main(String[] args) {
        String jsonLiteral = ""
                + "{\n"
                + "\tgreeting: \"Hello\",\n"
                + "\taudience: \"World\",\n"
                + "\tpunctuation: \"!\"\n"
                + "}\n";

        String jsonBlock = """
                {
                    greeting: "Hello",
                    audience: "World",
                    punctuation: "!"
                }
                """;

        System.out.println(jsonLiteral.equals(jsonBlock)); //false
        System.out.println(jsonBlock == jsonLiteral);
    }
}

What is it I am missing?


Solution

  • Let's make the Strings shorter.

    String jsonLiteral = ""
            + "{\n"
            + "\tgreeting: \"Hello\"\n"
            + "}\n";
    
    String jsonBlock = """
            {
                greeting: "Hello"
            }
            """;
    

    Let's debug them and print their actual content.

    "{\n\tgreeting: \"Hello\"\n}\n"
    "{\n    greeting: \"Hello\"\n}\n"
    

    \t and " " (four ASCII SP characters, or four spaces) aren't equal, neither are the whole Strings. As you may have noticed, the indentation in the text block was formed by spaces (not by horizontal tabs, or form feeds, or any other whitespace-like characters).

    Here are some examples of text blocks from the specification for JEP 355:

    String season = """
                    winter""";    // the six characters w i n t e r
    
    String period = """
                    winter
                    """;          // the seven characters w i n t e r LF
    
    String greeting = 
        """
        Hi, "Bob"
        """;        // the ten characters H i , SP " B o b " LF
    
    String salutation =
        """
        Hi,
         "Bob"
        """;        // the eleven characters H i , LF SP " B o b " LF
    
    String empty = """
                   """;      // the empty string (zero length)
    
    String quote = """
                   "
                   """;      // the two characters " LF
    
    String backslash = """
                       \\
                       """;  // the two characters \ LF
    

    In your case,

    String jsonBlock = """
              {
                  greeting: "Hello"
              }
              """; // the 26 characters { LF SP SP SP SP g r e e t i n g : SP " H e l l o " LF } LF
    

    To make them equal, replace "\t" with " ". Both equals and == should return true, though you shouldn't rely on the latter.


    To read:

    1. Specification for JEP 355: Text Blocks (Preview)

    Related:

    1. How the intents processed in a Text block(Java 13)

    2. illegal text block open delimiter sequence, missing line terminator