10. Mixing ordinary string literals with text blocks
Before mixing ordinary string literals with text blocks, let’s consider the following statement: How different is an ordinary string literal from a text block? We can answer this question via the following snippet of code:
String str = "I love Java!";
String txt = """
I love Java!""";
System.out.println(str == txt); // true
System.out.println(str.equals(txt)); // true
Wow! So our snippet of code prints true
twice. This means that an ordinary string literal and a text block are similar at runtime. We can define text blocks as string literals that span across multiple lines of text and use triple quotes as their opening and closing delimiter. How so? First, the instance produced from an ordinary string literal and a text block is of type java.lang.String
. Second, we have to look at the compiler internals. Basically, the compiler adds strings to a special cached...