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 String
s 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 String
s. 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:
Related: