Just the opposite of padding a string on the right with zeros and spaces, this example will show how to left pad a string with zeros and spaces while using java, guava and apache commons. A use case could be if a social security number is stored as a number, any SSN that would start with a 0 would be removed. For instance, 005-111-2111 would be stored as 51112111. Since zero is a valid char that you would want to format to an end user, you could use the snippets below to format the SSN with leading zeros.
Straight up Java
This snippet will format a String with leading zeros using core jdk formatter. We will define a pattern with a width of 10 and provide 'levelup' as the object to inject to the String.format method. Then calling the String.replace method we will replace all spaces with a zero.
This snippet will format a String with leading spaces using core jdk String.format. Similar to above, we will define a pattern with a width of 10 and replace pass in 'levelup'. The remainder length will be padded with spaces.
This snippet will left pad a string with zeros using guava's Strings utility class. Using Strings.padStart we will pass in the String to prepend to, a total length of the string when it is done and the value it should add to the beginning.
This snippet will left pad a string with spaces using guava's Strings utility. Like above, we will use Strings.padStart passing in three variables. First the string to format with spaces, second the minimum length and third the character in this case a space.
This code snippet will right justify a string while padding it with zeros using apache commons StringUtils.leftpad. In other words, it will left pad a String with a specified String and size.
This snippet will use a pad function to prepend spaces to the beginning of a string of a specified length using apache commons StringUtils.leftPad.