Question
How can I include variable values in Java text blocks using placeholders?
String name = "World";
String greeting = """Hello, %s!""".formatted(name); // Java 15+
System.out.println(greeting); // Output: Hello, World!
Answer
In Java, a text block is a multi-line string literal that allows for easy formatting and readability. To dynamically include variable values within a text block, placeholders are often required. This can be achieved using the `String.format()` method or the new `String.formatted()` method introduced in Java 15.
String name = "World";
String greeting = String.format("""Hello, %s!""", name);
System.out.println(greeting); // Output: Hello, World!
Causes
- Text blocks define static strings but do not directly support variable interpolation.
- Using placeholders requires additional formatting methods.
Solutions
- Utilize `String.format()` or `.formatted()` methods to substitute variable values into the text block.
- For example, use `String greeting = String.format("Hello, %s!", name);` to include the variable `name` within the text block.
Common Mistakes
Mistake: Using text blocks expecting automatic variable substitution.
Solution: Always use formatting methods like `String.format()` or `.formatted()` to insert variable values.
Mistake: Not handling null values in placeholders.
Solution: Ensure that variables used in placeholders are initialized to avoid NullPointerExceptions.
Helpers
- Java text block
- placeholders in Java
- Java string formatting
- Java 15 features
- how to use text blocks in Java