Since 1.5, String.format() can be used to left/right pad a given string. Let’s see how it can be used to do that.

Here a simple example where the char “*” is used to pad strings shorter than 2.

public class StringPadding {
        public static String padRight(String s, int n) {
		return String.format("%1$-" + n + "s", s).replace(" ", "*");  
	}

	public static String padLeft(String s, int n) {
		return String.format("%1$" + n + "s", s).replace(" ", "*");  
	}

	public static void main(String args[]) throws Exception {
		System.out.println(padRight("1", 2));
		System.out.println(padRight("10", 2));
		System.out.println(padLeft("1", 2));
		System.out.println(padLeft("10", 2));
	}
}

ciao