# Use Text Block

# Description

Java 15 introduced Text Blocks (opens new window) to express String literals spanning several lines and significantly reduce the need for escape sequences.

This rule replaces multiline String concatenation expressions with Text Block String literals. Thus, removing some boilerplate code and increasing the readability of String expressions.

Requirements

  • Java 15

# Benefits

Reduces the need for escape sequences. Improves readability.

# Tags

# Code Changes

# Concatenation of HTML Code

Pre

String html = "" +
		"<html>\n" +
		"\t<head>\n" +
		"\t\t<meta charset=\"utf-8\">" +
		"\t</head>\n" +
		"\t<body class=\"default-view\" style=\"word-wrap: break-word;\">\n"+ 
		"\t\t<p>Hello, world</p>\n" + 
		"\t</body>\n"+
		"</html>\n";

Post

String html = """
		<html>
			<head>
				<meta charset="utf-8">
			</head>
			<body class="default-view" style="word-wrap: break-word;">
				<p>Hello, world</p>
			</body>
		</html>
		""";

# Java Code without Missing Line Break at End

Pre

String java = "" +
		"		ArrayList<String> list = new ArrayList<>();\n" +
		"		list.add(\"one\");\n" +
		"		list.add(\"two\");\n" +
		"		list.add(\"three\");";

Post

String java = """
				ArrayList<String> list = new ArrayList<>();
				list.add("one");
				list.add("two");
				list.add("three");\
		""";

# Concatenation with Integer Literals

Pre

String java = "" + 
		"		int[] intArray = new int[3];\n" + 
		"		intArray[" + 0 + "] = " + 10 + ";\n" + 
		"		intArray[" + 1 + "] = " + 20 + ";\n" + 
		"		intArray[" + 2 + "] = " + 30 + ";\n";

Post

String java = """
		int[] intArray = new int[3];
		intArray[0] = 10;
		intArray[1] = 20;
		intArray[2] = 30;
""";

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID UseTextBlock
First seen in jSparrow version 4.3.0
Minimum Java version 15
Remediation cost 5 min
Links