Java String.format() Method
How to fill numbers with zeros or strings with spaces in Java
Overview
Filling with zeros or spaces means padding a number or string so that it has a specified number of digits or characters.
For example, if you have the number “123” and the total width is 5 characters, filling the remaining 2 characters at the front with zeros gives “00123”.
Here, we will introduce how to fill numbers with zeros and strings with spaces in Java.
Using the String.format() Method
Using the format() method of the String class, you can easily fill numbers or strings.
String.format(String format, Object... args);
format: format stringargs: argument values
The format string has the following specifications. If you want to fill a value with zeros to make it 5 digits wide, use “%05d”.
%: A directive indicating that this is a format string.0: The fill character. Here, 0 is specified.5: The number of digits. Here, 5 digits.d: The type of the output value. Here, decimal.
Now let’s write code that fills values with zeros and spaces.
package com.devkuma.basic.string;
public class StringFormat {
public static void main(String[] args) {
System.out.println("0으로 채우기");
System.out.println(String.format("%03d", 123));
System.out.println(String.format("%04d", 123));
System.out.println(String.format("%05d", 123));
System.out.println("공백으로 채우기");
System.out.println(String.format("%3s", "ABC"));
System.out.println(String.format("%4s", "ABC"));
System.out.println(String.format("%5s", "ABC"));
}
}
Execution result:
0으로 채우기
123
0123
00123
공백으로 채우기
ABC
ABC
ABC