Introduction
Lengthy Strings in Java code becomes hard to read. Multiline String literals can be XML, JSON, HTML, SQL queries, Hibernate or JPA queries, etc.Example
String html = " <html>\r\n" + " <body>\r\n" + " <p>Hello, world</p>\r\n" + " </body>\r\n" + " </html>\r\n" ;
Solution
Thanks to the Text blocks feature introduced in Java 13. Now, these multiline String literals are more presentable in Java code.
1. Configuring Eclipse for Text Blocks
1.1 Requirments
- JDK 13
- Eclipse Version: 2020-03 (4.15.0)
1.2 Eclipse Error 1
String literal is not properly closed by a double-quote
1.2.1 Solution
Change the source of your program to 13 as shown in the following screenshot
![]() |
Java Source 13 |
1.3 Eclipse Error 2
Text Blocks is a preview feature and disabled by default. Use --enable-preview to enable
1.3.2 Eclipse Error Solution
Move your mouse to Enable preview features on project properties and enable it.
![]() |
Enable preview features on project properties |
Note: Eclipse does not provide the option to choose Java version 14 for now and if you try to run the example with JDK 14, you may observe the following exception
Error: LinkageError occurred while loading main class TextBlock
java.lang.UnsupportedClassVersionError: TextBlock (class file version 57.65535) was compiled with preview features that are unsupported. This version of the Java Runtime only recognizes preview features for class file version 58.65535
java.lang.UnsupportedClassVersionError: TextBlock (class file version 57.65535) was compiled with preview features that are unsupported. This version of the Java Runtime only recognizes preview features for class file version 58.65535
2.1 Text Block Example
public class TextBlock { public static void main(String[] args) { String html = """ <html> <body> <p>Hello, world</p> </body> </html> """; System.out.println(html); } }
2.2 Output
![]() |
Output |
Conclusion
Text blocks is not another data type. Text blocks feature helps the developers to make the multiline String literals readable.
Comments
Post a Comment