This new escape sequence "\<line terminator>" can be used when we do not want to include a new line character at the end of a line within a text block.
When used, this escape sequence effectively suppresses the new line character that gets implicitly included at the end of that line.
Below code shows the usage of this escape sequence
public class Main {
public static void main(String[] args) {
String poemTextBlock = """
The woods are lovely, dark and deep, \
But I have promises to keep,
And miles to go before I sleep, \
And miles to go before I sleep.
""";
System.out.println(poemTextBlock);
}
}
In this code, we have used the "\<line terminator>" escape sequence on 1st and 3rd lines within the text block.
This suppresses the new line character on the 1st and 3rd lines and produces the below output
When using this, take care to ensure that the "\" at the end of the line is immediately followed by the line terminator without leaving any blank spaces after the "\".
Leaving a blank space at the end accidentally will throw a compilation error stating "illegal escape character".
Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/03/Language-Features/Text-blocks/New-escape-sequence-2
No comments:
Post a Comment