Thursday, September 28, 2023

Java: String Block

4 min read
(Updated: Thursday, September 28, 2023)

1. 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

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
    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
    |text block

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!

You might want to check these out ↘

How Your Database Stands Up to the Ultimate Reliability Check: ACID rules

How Your Database Stands Up to the Ultimate Reliability Check: ACID rules

For IT professionals in database management, grasping the core principles that protect our digital transactions is essential. Today, we're exploring the ACID model, a pivotal framework for ensuring transaction reliability and security. This goes beyond mere theoretical knowledge; it's vital for the smooth operation of diverse systems, from financial processes to social media platforms. We'll delve into the ACID principles and their critical role in real-world applications.
Convert String to Date: The Java Ways

Convert String to Date: The Java Ways

Converting strings to dates in programming is a common task that's more complex than it seems. This challenge is rooted in the wide range of date formats and the specifics of time zones. Converting a String to a Date in Java can be done in several ways, depending on the Java version you're using and whether you are incorporating external libraries. Below are the primary methods used in different versions of Java and through some commonly used external libraries.
Cookbook: How to Effectively Revert a Git Commit

Cookbook: How to Effectively Revert a Git Commit

As a software engineer, encountering situations where recent changes need to be undone is not uncommon. It may be due to errors, or in some cases just need a significant rework. When such scenarios arise while using Git as your version control system, there’s a few approaches that can help revert those changes effectively. Let’s take a closer look.
Contact Us

Stay ahead of the curve
on software insights and technology trends.