Convert integer to equivalent number of blank spaces

You can create a char[] of the desired length, Arrays.fill it with spaces, and then create a String out of it (or just append to your own StringBuilder etc).

import java.util.Arrays;

int n = 6;
char[] spaces = new char[n];
Arrays.fill(spaces, ' ');
System.out.println(new String(spaces) + "!");
// prints "      !"

If you're doing this with a lot of possible values of n, instead of creating and filling new char[n] every time, you can create just one long enough string of spaces and take shorter substring as needed.


I think you meant something like:

    int n = 6;
    String s = String.format("%1$"+n+"s", "");

System.out.format("[%13s]%n", "");  // prints "[             ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[   ]" (3 spaces)