Java: String Block
4 min read1. Introduction
Java JDK 17 introduces a new feature called “String Block”, which significantly improves the handling of multiline strings in Java. This feature aims to simplify the creation and manipulation of multiline strings, making Java code more readable and maintainable.
In this session, we will delve into the new String Block feature, explore its benefits, and work through some code examples. Additionally, we will compare Java’s implementation with similar features in other programming languages.
2. What is a String Block?
A String Block, introduced as a preview feature in JDK 13 and finalized in JDK 17, allows developers to create multiline strings with ease. Instead of concatenating strings line by line or using escape sequences, developers can now use triple quotes “”” to define a multiline string block. This feature provides a more elegant and readable way to define multiline strings, making it easier to work with large blocks of text or code snippets.
String json = """
{
"name": "John Doe",
"age": 45,
"address": "Doe Street, 23, Java Town"
}
""";
3. Whitespace Handling
One of the benefits of String Blocks is the improved handling of whitespaces. Any leading or trailing spaces in a String Block are removed, and indentation is automatically calculated based on the least indented line.
This makes it easier to work with strings that require specific formatting, such as code snippets or SQL queries. For example:
String sqlQuery = """
SELECT name, age, email
FROM users
WHERE age > 18
ORDER BY name ASC""";
Automatic line breaks are added at the end of each line, and you can control the indentation by placing the closing triple quotes at the desired indentation level. If you need to remove any extra whitespaces, you can use the stripIndent() method:
String strippedString = """
This string will
have its indentation
stripped.""".stripIndent();
4. Why is String Block Useful?
String Block offers a number of advantages over the previous method of defining multi-line Strings:
- Improved Readability: With String Block, the text is indented and formatted in a way that makes it easier to read and understand.
- Easier Maintenance: String Block makes it easier to make changes to multi-line Strings, since you can simply edit the text within the triple quotes.
- Reduced Errors: Since String Block eliminates the need for concatenation, there is less chance of errors occurring due to missing or misplaced quotes or operators.
5. String block in other languages
String Block is not a new concept, and other modern programming languages have already been using similar syntax.
Here’s a glance of some of them.
5.1 Python
Python uses triple quotes (”’ or “””) to denote multi-line strings, which is similar to Java JDK 17’s String Blocks.
multi_line_string = """
This is a multi-line
string in Python."""
5.2 JavaScript
JavaScript (ES6+): JavaScript introduced Template Literals with backticks (`) to support multi-line strings and string interpolation.
const multiLineString = `
This is a multi-line
string in JavaScript.`;
5.3 Kotlin
Kotlin is another popular programming language that has a similar feature to Java's String Block called "Raw String Literals". Kotlin's Raw String Literals allow developers to define string literals without having to escape special characters or use concatenation to represent multi-line strings. Here's an example of how to use Raw String Literals in Kotlin:
val textBlock = """
This is a
multi-line
text block
"""
As you can see, the syntax is very similar to Java's String Block syntax, with triple quotes used to define the text block.
6. One more thing
One key difference between Kotlin's Raw String Literals and Java's String Block is that Kotlin also allows developers to define "Trimmed String Literals". These are similar to Raw String Literals, but with leading and trailing whitespace trimmed automatically. Here's an example of a Trimmed String Literal in Kotlin:
val trimmedTextBlock = """
|This is a
|multi-line
|text block
""".trimMargin()
In this example, the trimMargin() function is used to remove the leading | characters that are used to align the text block. This is a useful feature for when you need to define text that spans multiple lines but also needs to be formatted in a specific way. Overall, Kotlin's Raw String Literals and Java's String Block are very similar in terms of their syntax and functionality. Both are useful tools for working with string literals, and both make it easier to write readable and maintainable code.
7. Conclusion
Now that we have seen the feature of String Block, where it providing a more convenient and efficient way to handle multi-line String literals in the code, its improved readability, easier maintenance, and reduced errors. If you looking for a better way to handle multi-line Strings in your code, give String Block a try when coming across it!