What is Text Blocks in Java?
Do you want to insert HTML text, Simple multiline Text String to your Java code? Well, Text Blocks in Java 15
is a solution to that. No need for you to worry about Escape Character.
In this tutorial we will go over different Java 15 Text Blocks Examples.
Let’s get started:
Create Java class: CrunchifyJava15TextBlocks.java
Copy below code and save file.
package crunchify.com.tutorial; /** * @author Crunchify.com * Version: 1.0 * Java 15 Text Blocks Example */ public class CrunchifyJava15TextBlocks { public static void main(String[] args) { // JAVA 15 HTML Text Blocks String java15HTML = """ <html> <body> <p>Hey.. This is test example on Java 15 Text Blocks by Crunchify.com</p> </body> </html> """; System.out.println(java15HTML); // Before Java 15: string literals String beforeJava15HTML = "<html>\n" + " <body>\n" + " <p>Hey.. This is test example on Java 15 Text Blocks by Crunchify.com</p>\n" + " </body>\n" + "</html>\n"; System.out.println(beforeJava15HTML); // Java 15: SQL Query format String java15Query = """ SELECT "EMP_NAME", "EMP_LAST_NAME" FROM "CRUNCHIFY_TABLE" WHERE "CITY" = 'NEWYORK' ORDER BY "EMP_NAME"; """; System.out.println(java15Query); // Before Java 15: SQL Query using string literals String beforeJava15Query = "SELECT \"EMP_NAME\", \"EMP_LAST_NAME\" FROM \"CRUNCHIFY_TABLE\"\n" + "WHERE \"CITY\" = 'NEWYORK'\n" + "ORDER BY \"EMP_NAME\";\n"; System.out.println(beforeJava15Query); } }
Simply run above Java program and you should see result same as below.
Console output:
IntelliJ IDEA Console result.
/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=49589:/Applications/IntelliJ IDEA.app/Contents/bin <html> <body> <p>Hey.. This is test example on Java 15 Text Blocks by Crunchify.com</p> </body> </html> <html> <body> <p>Hey.. This is test example on Java 15 Text Blocks by Crunchify.com</p> </body> </html> SELECT "EMP_NAME", "EMP_LAST_NAME" FROM "CRUNCHIFY_TABLE" WHERE "CITY" = 'NEWYORK' ORDER BY "EMP_NAME"; SELECT "EMP_NAME", "EMP_LAST_NAME" FROM "CRUNCHIFY_TABLE" WHERE "CITY" = 'NEWYORK' ORDER BY "EMP_NAME"; Process finished with exit code 0
Make sure you set Java Runtime to 15.
If you are using IntelliJ IDEA then it also suggests to use Java 15 Text Blocks if you are using String literal in code.
Let me know if you face any issue running Java 15 – Text Blocks code.