Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 692
Wojciech Wirzbicki Avatar asked May 12 '26 00:05

Wojciech Wirzbicki


1 Answers

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
like image 129
Wojciech Wirzbicki Avatar answered May 13 '26 15:05

Wojciech Wirzbicki