Search code examples
javastring-formatting

What does this 'String.format("...");' in Java do?


String.format("%-" + 3 + "." + 3 + "s", givenString);

This is supposed to add white spaces but it doesn't. I tried it on an online compiler and it adds up the numbers to the string. I don't understand what that's doing. Could someone explain?


Solution

  • public static String format(String format, Object... args) - this is the method declaration.

    String format = "%-" + 3 + '.' + 3 + 's';   // = %-3.3s
    String.format(format, givenString);
    

    This is used to build format dynamically, but it does not have variables in it, so you could replace it with String.format("%-3.3s", givenString);

    According to format, this prints a string with a maximum of 3 characters in length. It reserves 3 symbols per line and it will be left justified in case givenString is less than 3 characters long.

    Demo:

    System.out.println(String.format("%-3.3s", "ab"));  // "ab "
    System.out.println(String.format("%-3.3s", "abc"));  // "abc"
    System.out.println(String.format("%-3.3s", "abcd"));  // "abc"
    System.out.println(String.format("%-3.3s", "a") + String.format("%-3.3s", "b"));  // "a  b  "
    

    See more in Documentation