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.

Answer from Martin Törnwall on Stack Overflow
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) });
🌐
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
Discussions

How to format a number starts with zero.
Don't read the number as a number, read it as a String - and treat it as a String. Just because something only consists of numbers doesn't mean that it should be stored as a number. More on reddit.com
🌐 r/learnjava
9
4
February 13, 2019
String.Format
Is it possible to create a string from an int with leading 0's using String.Format() ? e.g. i have the int value of 1 and i want to create a string containing "00000001" Thanks, More on thecodingforums.com
🌐 thecodingforums.com
4
April 21, 2005
Why does Java string formatting %f always show 6 digits after the comma
%f for floating point so it work for double and float type and the 6 number after the decimal point is the default if you want to change it to 3 for example System.out.println(String.format("%.3f", 30.0F)); this the formater option you have https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Formatter.html hope that help and have a nice day :) More on reddit.com
🌐 r/javahelp
3
0
September 28, 2022
How to preserve leading zeroes while converting an integer to string?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
6
1
August 9, 2024
🌐
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 ...
🌐
Baeldung
baeldung.com › home › java › java string › java string.format()
Java String.format() | Baeldung
March 23, 2026 - This exception typically occurs ... with a string. When padding integers, we should use d for the integer and 0 for the padding flag....
🌐
Jmu
wiki.cs.jmu.edu › reference › java › formatting
Formatting Strings and Output in Java - JMU CS Wiki
January 26, 2026 - 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).
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-format-method-with-examples
Java String format() Method - GeeksforGeeks
June 2, 2026 - Supports formatting of numbers, strings, dates, and other data types. Uses format specifiers such as %s, %d, %f, and %c. Example: Java program to demonstrate working of format() method
Find elsewhere
🌐
Coderanch
coderanch.com › t › 623115 › java › java-String-format
Using java String.format() [Solved] (Beginning Java forum at Coderanch)
November 4, 2013 - This is my code for the string: This is my current output and my format string is: String format = "%-4s %-20s d"; (I used the 0's to keep track of where the itemName Ends) Based on this tutorial, -4s would mean that my itemNumber takes up 4 spaces and will be left justified, then my itemName will take up 20 spaces and would be left justified, then 04d would right justify my itemValue and pad it with 0's to the left if the value does not take up 4 character spaces.
🌐
Coderanch
coderanch.com › t › 381807 › java › Format-number-string-include-leading
Format number string to include leading zeros (Java in General forum at Coderanch)
January 8, 2007 - For your problem as described, Integer.parseInt() would be a better fit - but the idea is the same. And if you're using JDK 5+, you can use a format string to make this a little more compact: You may also want to ask yourself: what if the user enters something invalid in the text field?
🌐
Read Learn Code
readlearncode.com › 2017 › 09 › 20 › how-to-format-a-string-clarified
How to Format a String, Clarified! – Read Learn Code
May 14, 2025 - String.format("An hex number %x", 100); // An hex number 64 String.format("An hex number %#X", 100); // An hex number 0X64 · Note the capital X in the last example. The case of the X determines the case of the X in the output number i.e. a lowercase x results in a lowercase X in the output number. To round-up what I have talked about so far I have prepared a table summarising the flags. This is not an exhaustive list, for you must consult the Java documentation.
🌐
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 a String using Java String format() method.
🌐
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 - Use String.format("d", value) to pad an integer with leading zeros to a fixed width. The 0 flag tells the formatter to pad with zeros instead of spaces,...
🌐
Quora
quora.com › How-do-you-add-a-zero-in-front-of-a-string-in-Java
How to add a zero in front of a string in Java - Quora
Answer (1 of 2): Short and Simple answer, you can directly do something like this. > [code]String str = "Some String";//let's assume this is the string. str = "0" + str;//This will add '0' in front of the String str. [/code] This code works. But Is that a best practice? No! String concatenation...
🌐
CodeGym
codegym.cc › java blog › strings in java › java string format()
Java String format()
The number of arguments for the format string ranges from 0 to many. Returns It always returns the formatted string according to the locale.
Published: December 24, 2024
🌐
LeetCode
leetcode.com › problems › add-strings
Add Strings - LeetCode
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. Example 1: Input: num1 = "11", num2 = "123" Output: "134" Example 2: Input: num1 = "456", num2 = "77" Output: "533" Example 3: Input: num1 = "0", num2 = "0" Output: "0" Constraints: 1 <= num1.length, num2.length <= 104 ·
🌐
Reddit
reddit.com › r/learnjava › how to format a number starts with zero.
r/learnjava on Reddit: How to format a number starts with zero.
February 13, 2019 -

Hello, so I have a question to check whether a number is a palindrome or not, (a palindrome is a number that you read the same if you read it digit by digit from left to right or vice versa). keeping in mind you must enter only 5 digits, However I don't know how to deal with it if the user enters 0 for example 02120 is palindrome, however, java omit the first zero so it's considered as a non palindrome.

Here is what I managed to so so far but it doesn't work with numbers starting with 0 .

thank you.

🌐
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 ·
🌐
DZone
dzone.com › data engineering › data › comprehensive guide to java string formatting
Comprehensive Guide to Java String Format in 2021
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());...
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
String.Format | Java | Coding Forums
April 21, 2005 - It is all in the API documentation. Use a width of your choice and the zero-padding flag, just like it is done in good old C: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax /Thomas ·
🌐
Attacomsian
attacomsian.com › blog › java-string-format
How to format a string in Java
October 29, 2022 - A quick guide to learn how to use the String.format() method and the MessageFormat class to format strings in Java.
🌐
Novixys Software
novixys.com › blog › java-string-format-examples
Java String Format Examples | Novixys Software Dev Blog
February 4, 2018 - String.format("|0.5s|", "Hello World"); | Hello| This guide explained String formatting in Java. We covered the supported format specifiers. Both numeric and string formatting support a variety of flags for alternative formats. Java 9 Modules Tutorial - Getting Started ·