Sunday, 23 May 2021

Java14: text blocks

Text blocks are already added in Java13 as preview feature (https://openjdk.java.net/jeps/355). It is further enhancement to this preview feature (https://openjdk.java.net/jeps/368).

 

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>

			""";

 

you can use newlines, special characters etc., in the text blocks without any escaping.

 

TextBlockDemo1.java

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

 

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

 

Reference

https://openjdk.java.net/jeps/368

 


 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment