public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}
Answer from Alex Rashkov on Stack Overflow
🌐
Codemia
codemia.io › home › knowledge hub › how to format a java string with leading zero?
How to format a Java string with leading zero? | Codemia
January 27, 2025 - The 0 flag tells the formatter to pad with zeros instead of spaces, and the number after it specifies the total width. For example, String.format("d", 42) produces "00042". ... This is the standard approach in Java for invoice numbers, time components, file naming, and any situation where ...
🌐
Jmu
wiki.cs.jmu.edu › reference › java › formatting
Formatting Strings and Output in Java - JMU CS Wiki
January 26, 2026 - In the above example, the format specifier is =. Format specifiers have the following syntax. ... Common values of conversion include b for boolean, c for char, d for int, e for double in scientific notation, f for double, and s for String. Common values of the optional flag include - for left-justified, + to always include the sign, 0 to pad with zeros, , to use grouping separators, ( to put negative numbers in parentheses, and a space character to use a space for the sign of a positive number (as opposed to omitting it).
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-string-format-method
Java String format() method
June 9, 2024 - The important point to remember is that the format specifiers for these are different. %s – for strings %f – for floats %d – for integers · public class Example{ public static void main(String args[]){ int str = 88; /* Left padding an integer number with 0's and converting it * into ...
🌐
W3Schools
w3schools.com › java › ref_string_format.asp
Java String format() Method
Strings Concatenation Numbers and Strings Special Characters Code Challenge Java Math Java Booleans · Booleans Real-Life Example Code Challenge Java If...Else
🌐
Baeldung
baeldung.com › home › java › java string › java string.format()
Java String.format() | Baeldung
March 23, 2026 - This exception typically occurs when we try to use a format specifier with a data type that isn’t compatible with it, e.g., trying to use %s (for string) with an integer, or %d (for decimal integer) with a string. When padding integers, we should use d for the integer and 0 for the padding flag.
🌐
Dot Net Perls
dotnetperls.com › format-java
Java - String.format Examples - Dot Net Perls
Many format codes can be used with String.format. Here we pad a number with zeros on the left side. The first 0 means "pad with zeros" and the 5 means "use five digits."
🌐
Baeldung
baeldung.com › home › java › java string › pad a string with zeros or spaces in java
Pad a String with Zeros or Spaces in Java | Baeldung
May 11, 2024 - StringBuilder sb = new StringBuilder(); ... Finally, since Java 5, we can use String.format(): return String.format("%1$" + length + "s", inputString).replace(' ', '0'); We should note that by default the padding operation will ...
Find elsewhere
Top answer
1 of 12
323

Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:

String.format("Hello %s, %d", "world", 42);

…would return "Hello world, 42". The "format string" link points to the complete official spec, but for simple cases, this much shorter documentation may be helpful for an introduction to format specifiers even though it's outdated and about Lava. The most commonly used ones are:

  • %s - insert a string
  • %d - insert a signed integer (decimal)
  • %f - insert a real number, standard notation

This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:

String.format("The {0} is repeated again: {0}", "word");

... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)


If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.

2 of 12
182

In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.

For example:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
🌐
Programiz
programiz.com › java-programming › library › string › format
Java String format()
System.out.println(String.format("%#o", n)); // 056 System.out.println(String.format("%#x", n)); // 0x2e } } The String format() method also has another syntax if you have to work with the specified locale. String.format(Locale l, String format, Object... args) // to use Locale import java.util.Locale; class Main { public static void main(String[] args) { int number = 8652145; String result; // using the current locale ·
🌐
Mkyong
mkyong.com › home › java › java string format examples
Java String Format Examples - Mkyong.com
March 10, 2020 - // 1100100 String result1 = String.format("%s", Integer.toBinaryString(100)); // 00000000000000000000000001100100 String result2 = String.format("2s", Integer.toBinaryString(100)).replace(" ", "0"); // 00000000000000011110001001000000 String ...
🌐
Blogger
javarevisited.blogspot.com › 2013 › 02 › add-leading-zeros-to-integers-Java-String-left-padding-example-program.html
How to Add Leading Zeros to Integers in Java ? String Left Padding Example Program
The format() method of String class in Java 5 is the first choice. You just need to add "d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.
🌐
W3Docs
w3docs.com › java
Left padding a String with Zeros | W3Docs
You can also use the DecimalFormat class to left pad a string with zeros. For example: ... String s = "123"; DecimalFormat df = new DecimalFormat("00000"); String padded = df.format(Integer.parseInt(s)); // padded is "00123"
🌐
DZone
dzone.com › data engineering › data › comprehensive guide to java string formatting
Comprehensive Guide to Java String Format in 2021 - DZone
July 15, 2021 - For example, if we want to print ... following: ... String formattedString = MessageFormat.format("Int: {0,number,integer}, date: {1,date}", 117, new Date());...
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › lang › string
String.format Java Example - Examples Java Code Geeks - 2026
November 9, 2023 - For example, the + flag specifies that a numeric value should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include – that is pad on the right, + pad on the left (if the formatted object ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 7 )
Every method which produces formatted output requires a format string and an argument list. The format string is a String which may contain fixed text and one or more embedded format specifiers. Consider the following example:
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, BigDecimal, and Calendar are supported.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-add-leading-zeros-to-a-number
Java Program to add leading zeros to a number
June 26, 2020 - Let’s say we need to add 4 leading zeros to the following number with 3 digits. int val = 290; For adding 4 leading zeros above, we will use d i.e. 4+3 = 7. Here, 3, as shown above, is the number with 3 digits.