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?
Let's make the
Strings shorter.Let's debug them and print their actual content.
\tand" "(four ASCII SP characters, or four spaces) aren't equal, neither are the wholeStrings. 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:
In your case,
To make them equal, replace
"\t"with" ". Bothequalsand==should returntrue, though you shouldn't rely on the latter.To read:
Related:
How the intents processed in a Text block(Java 13)
illegal text block open delimiter sequence, missing line terminator