When programming, sometimes you need to store a multi-line text in one String variable. So instead of having multiple variables of type String and then, joining all of them into one I recommend using Java feature called Text Blocks.
Compared to a simple String variable, a text block has to start with a triple quotation mark.
//regular String variables
String greeting = "Welcome to Dastin Sandura's blogspot!";
String description = "I blog about the practical use of Java language."
For comparison, below is a String, initialized with a text block.
//text block stored in String variable
String multiLineGreeting = """
Welcome to Dastin Sandura's blogspot!
I blog about the practical use of Java language.""";
Both of the variables presented above are of type String, which means that by looking at a variable type you cannot tell if its value was set, by using the text block Java feature.
However, the most critical difference between the initialization of these two variables, is that the regular string uses a single quotation mark to mark the beginning and the end of the value, and the text block uses three quotation marks and a new line. Using text block without inserting a new line after three quotation marks will not pass the compilation.
Another difference is in the number of variables that we had to create. In the first case, we created a variable for each line.
Although, instead of creating a new variable for each line we could simply use the new line character (\n) and make the first code block look like this:
//regular String variable with new line special character
String greeting = "Welcome to Dastin Sandura's blogspot!\n"
+"I blog about the practical use of Java language."
We have removed the second variable and added a special character and a concatenation of two string variables.
This makes the code harder to read, due to characters that are visible in the code but will not be visible when printing the string to the view.
Sources:
"Programmer's Guide to Text Blocks" - https://docs.oracle.com/en/java/javase/17/text-blocks/index.html
Comments
Post a Comment