Text blocks are available in Java13 as preview feature. Text blocks start with a """ (three double-quote marks) followed by optional white space and a newline.
Example
String str1 = """
<html>
<head><title>Hello World</title></head>
<body>
<h1>Java13 Hello World application</h1>
</body>
</html>
""";
Inside text blocks, you can use newlines, special characters etc., without any escaping.
TextBlockDemo1.java
package com.sample.app.strings;
public class TextBlockDemo1 {
public static void main(String args[]) {
String str1 = """
<html>
<head><title>Hello World</title></head>
<body>
<h1>Java13 Hello World application</h1>
</body>
</html>
""";
System.out.println(str1);
}
}
Output
<html> <head><title>Hello World</title></head> <body> <h1>Java13 Hello World application</h1> </body> </html>
To support variable substitution, 'formatted' method is added in String class.
@Deprecated(forRemoval=true, since="13")
public String formatted(Object... args)
This method is associated with text blocks, a preview language feature. Text blocks and/or this method may be changed or removed in a future release. Formats using this string as the format string, and the supplied arguments.
TextBlockDemo2.java
package com.sample.app.strings;
public class TextBlockDemo2 {
public static void main(String args[]) {
String name = "Krishna";
int age = 32;
String message = """
Hi %s, you are %d years old
""".formatted(name, age);
System.out.println(message);
}
}
Output
Hi Krishna, you are 32 years old
No comments:
Post a Comment