Search code examples
javastringformattingstring-formatting

formatting a string :%20s


Hi I'm new to java programming while trying to write some simple codes I saw this formatted string I know how it works but my question is about the integer we put between % and s ... at first i thought it might be about the length of the blank field like if it is 5 we will see 5 space characters but i was wrong

if we put any integer smaller than 20 it wont work at all and when i put 20 the field length was 9 space characters...

i would appreciate if you could help me


Solution

  • %20s means your String will be left-padded if its length is less than 20.

    • If your String is length characters long with length<20, then it will add (20-length) space characters to the left.
    • If your String is more than 20 characters, then nothing is added (and the String is not truncated)

    Examples:

    System.out.println(":" + String.format("%20s", "HelloWorld") + ":");
    :          HelloWorld:
    
    System.out.println(":" + String.format("%20s", "Damn this is a long string") + ":");
    :Damn this is a long string: