javajava-text-blocks

Java text block indentation and leading spaces


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

Solution

  • 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