0

Given the following code

public class TextBlock {

    public static void main(String[] args) {
        String indentedText = """
            hello
                indented
            world
        """;
        System.out.println(indentedText);
    }
}

The output is as follows (mind the leading spaces):

    hello
        indented
    world

How to obtain String value like below (without unnecessary leading spaces)?

hello
    indented
world
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
  • 2
    This is specified in the Java Language Specification [3.10.6. Text Blocks](https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.10.6): *"Incidental white space is removed, as if by execution of `String.stripIndent`"* and detailed in [`stripIndent()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#stripIndent()) or even a [Programmer's Guide to Text Blocks](https://docs.oracle.com/en/java/javase/16/text-blocks/index.html) from Oracle – user16320675 Feb 01 '22 at 16:18

1 Answers1

7

You can manipulate indentation by changing closing quotes position in the code ("""). For example

String indentedText = """
                hello
                    indented
                world
    """;
System.out.println(indentedText);

Would produce

        hello
            indented
        world

but

String indentedText = """
                hello
                    indented
                world
                """;
System.out.println(indentedText);

will produce

hello
    indented
world
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59