Java text block indentation and leading spaces

1.5k Views Asked by At

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
1

There are 1 best solutions below

0
On BEST ANSWER

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