Java Raw String Literals (JEP 378)
Java 16 introduced raw string literals, which are a new kind of string literal that allows you to create multi-line strings in a more readable and maintainable way. Raw string literals are created by enclosing the string in triple quotation marks ("""
), and they do not interpret escape sequences or white space.
Here is an example of how to use raw string literals in Java:
String html = """
<html>
<body>
<p>Hello, World!</p>
</body>
</html>
""";
In this example, the html
variable is initialized with a string that contains multiple lines of HTML code. Because the string is defined using raw string literals, the white space and line breaks are preserved as they are written in the code, which makes the string easier to read and maintain.
Raw string literals can be used in a variety of contexts, such as in string concatenation, string interpolation, and regular expressions. They can also be used in conjunction with other string literals, such as escape sequences and Unicode escapes.
One important thing to note about raw string literals is that they are not suitable for all cases. In particular, they may not be suitable for strings that contain sensitive information or that need to be localized, as they do not support escape sequences or string formatting.