<< Back to JAVA
Java String.format Examples: Numbers and Strings
Use String.format to create strings with variables inserted in them. Handle integers and strings.Format. Often we need to compose strings from variables (like integers) and other text. String.format is ideal here. It provides a format language to which we add variables.
To insert numbers, we can use the "d" format. We use ordinals after the initial "%" symbol, starting at 1 and increasing. This indicates which argument to insert.
Integers, d format. This is a good first example. We add the values 10, 20 and 30 to a format string. We specify the format string as the first argument to format.
And: We specify, after the "$" sign that we want to insert numbers (digits) with the lowercase "d" char.
Result: Format yields a composed string containing text (number words), punctuation, and numeric values.
Java program that uses String.format
public class Program {
public static void main(String[] args) {
// Call String.format with three integer codes.
String result = String.format("One: %1$d Two: %2$d Three: %3$d",
10, 20, 30);
System.out.println(result);
}
}
Output
One: 10 Two: 20 Three: 30
Pad with zeros. 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."
Java program that pads with zeros
public class Program {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// Pad with zeros and a width of 5 chars.
String result = String.format("%1$05d %2$05d", i, i + 10);
System.out.println(result);
}
}
}
Output
00000 00010
00001 00011
00002 00012
00003 00013
00004 00014
Precision, double. We can specify the precision of a double or float. We use the "f" to indicate a floating-point. Before this we specify ".3" to mean "three numbers after the decimal."
Note: As this example shows, the "f" format will round the number up, not truncate digits.
Java program that uses precision
public class Program {
public static void main(String[] args) {
double number = 1.23456;
// Specify precision with format.
String value = String.format("Three numbers after decimal: %1$.3f",
number);
System.out.println(value);
}
}
Output
Three numbers after decimal: 1.235
Insert strings. We can insert a string with the "s" format. This example shows three different syntax forms. We can specify just "%s," use the percentage sign "%," or use a "$" in between.
Index: It helps to use an index to reference the argument (like "%1") if we reuse the argument, or the references are different in order.
Opinion: I think just using "%s" when possible yields the clearest, easiest-to-read code. Keep it simple.
Java program that inserts string with format
public class Program {
public static void main(String[] args) {
String first = "Marcus";
String last = "Aurelius";
// Use simple string format.
String value = String.format("%s %s", first, last);
System.out.println(value);
// Use indexes before simple string format.
value = String.format("%1s %2s", first, last);
System.out.println(value);
// Use $ symbol before string character.
value = String.format("%1$s %2$s", first, last);
System.out.println(value);
}
}
Output
Marcus Aurelius
Marcus Aurelius
Marcus Aurelius
Argument order. This example uses both a string and an integer in one format string. It also inserts the second argument first—it uses the "%2" syntax for this.
Java program that reorders arguments
public class Program {
public static void main(String[] args) {
String id = "ART1";
int number = 100;
// Place the last argument first.
// ... Use integer and string in same format string.
String value = String.format("%2$d %1$s", id, number);
System.out.println(value);
}
}
Output
100 ART1
Padding, right and left. Here we use right-padding and left-padding in a format string. We can apply padding to strings, numbers or other values.
PaddingRight: To specify padding on the right (ten spaces on the right) we use -10s. The result string is 10 chars.
Left: To add padding to the left (right justify text) to 10 chars, we use 10s. No plus sign is used.
Java program that uses padding, right and left
public class Program {
public static void main(String[] args) {
String[] lefts = { "cat", "dog", "bird", "elephant" };
String[] rights = { "orange", "black", "blue", "grey" };
// Loop over both arrays and display paired strings.
for (int i = 0; i < lefts.length; i++) {
String left = lefts[i];
String right = rights[i];
// Add padding to the right.
// ... Add padding to the left.
String value = String.format("%1$-10s %2$10s", left, right);
System.out.println(value);
}
}
}
Output
cat orange
dog black
bird blue
elephant grey
Calendar. This example uses String.format with a Calendar date. We use "tB" to insert the long month string (like January). With "te" and "tY" we insert the day and year numbers.
CalendarNote: We use the "%1" at the start of the insertion points to indicate "the first argument" after the format string.
Java program that uses format, Calendar
import java.util.Calendar;
public class Program {
public static void main(String[] args) {
// Create a calendar with a specific date.
Calendar cal = Calendar.getInstance();
cal.set(2015, 0, 15);
// Format the month, day and year into a string.
String result = String.format("Month: %1$tB Day: %1$te Year: %1$tY",
cal);
System.out.println(result);
}
}
Output
Month: January Day: 15 Year: 2015
Months, days, years. This example shows various ways of formatting months, days, and years with String.format. We specify formatting with uppercase or lowercase letters after the "t."
Month: The uppercase "B" is along month name like February. The lowercase "b" is a short name like Feb. And "m" means the month number.
Day: With "A" we use the long day name like Wednesday. With "a" we specify the short name like Wed. The "d" is a day number.
Year: An uppercase Y is the long year like 2015. A lowercase "y" is a two-digit year. A "j" is the day number in an entire year.
Java program that formats months, days and years
import java.util.Calendar;
public class Program {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2015, 1, 18);
// Format the month.
String result = String.format("Month: %1$tB %1$tb %1$tm", cal);
System.out.println(result);
// Format the day.
result = String.format("Day: %1$tA %1$ta %1$td", cal);
System.out.println(result);
// Format the year.
result = String.format("Year: %1$tY %1$ty %1$tj", cal);
System.out.println(result);
}
}
Output
Month: February Feb 02
Day: Wednesday Wed 18
Year: 2015 15 049
Hour, minute and second. This is starting to become confusing. Here we format hours, minutes and seconds with String.format. Hours can be formatted in many ways.
Hours: We use the chars "HIkl" to format hours. The H means 2-digits on the 24-hour clock. The "k" is the same as H but has no leading 0.
Hours, 12-hour: The 12-hour clock requires the uppercase letter I in the format. With "l" we have the same thing but with no leading 0.
AM/PM: The difference between AM and PM is critical in life. With the lowercase p format code we get am and pm strings.
Java program that formats hour, minute, second, AM and PM
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
public class Program {
public static void main(String[] args) {
// Set time to current time.
Calendar cal = Calendar.getInstance();
cal.setTime(Date.from(Instant.now()));
// Format the hour.
String result = String.format("Hour: %1$tH %1$tI %1$tk %1$tl", cal);
System.out.println(result);
// Format minute.
result = String.format("Minute: %1$tM", cal);
System.out.println(result);
// Format the second.
result = String.format("Second: %1$tS", cal);
System.out.println(result);
// Format the am and pm part.
result = String.format("AM/PM: %1$tp", cal);
System.out.println(result);
}
}
Output
Hour: 18 06 18 6
Minute: 53
Second: 23
AM/PM: pm
Filenames. Sometimes we have a program that generates files on a regular basis (on a schedule). We can generate filenames with String.format that contain the current date and time.
Filename Date
A summary. With String.format, a format string is used to insert values (as from variables). We add punctuation and text data in between insertions.
Advanced features. With format, we can change how numbers are displayed. We can pad with zeros and change how far past the decimal place we go. This is powerful and useful.
Related Links:
- Java Continue Keyword
- Java Convert Char Array to String
- Java Combine Arrays
- Java Console Examples
- Java Web Services Tutorial
- Java Odd and Even Numbers: Modulo Division
- Java IO
- Java 9 Features
- Java 8 Features
- Java String
- Java Regex | Regular Expression
- Java Filename With Date Example (Format String)
- Java Applet Tutorial
- Java Files.Copy: Copy File
- Java filter Example: findFirst, IntStream
- Java Final and final static Constants
- Java Super: Parent Class
- Java Date and Time
- Java do while loop
- Java Break
- Java Continue
- Java Comments
- Java Splitter Examples: split, splitToList
- Java Math.sqrt Method: java.lang.Math.sqrt
- Java Reflection
- Java Convert String to int
- JDBC Tutorial | What is Java Database Connectivity(JDBC)
- Java main() method
- Java HashMap Examples
- Java HashSet Examples
- Java Arrays.binarySearch
- Java Integer.bitCount and toBinaryString
- Java Overload Method Example
- Java First Words in String
- Java Convert ArrayList to String
- Java Convert boolean to int (Ternary Method)
- Java regionMatches Example and Performance
- Java ArrayDeque Examples
- Java ArrayList add and addAll (Insert Elements)
- Java ArrayList Clear
- Java ArrayList int, Integer Example
- Java ArrayList Examples
- Java Boolean Examples
- Java break Statement
- Java Newline Examples: System.lineSeparator
- Java Stream: Arrays.stream and ArrayList stream
- Java charAt Examples (String For Loop)
- Java Programs | Java Programming Examples
- Java OOPs Concepts
- Java Naming Conventions
- Java Constructor
- Java Class Example
- Java indexOf Examples
- Java Collections.addAll: Add Array to ArrayList
- Java Compound Interest
- Java Int Array
- Java Interface Examples
- Java 2D Array Examples
- Java Remove HTML Tags
- Java Stack Examples: java.util.Stack
- Java Enum Examples
- Java EnumMap Examples
- Java StackOverflowError
- Java startsWith and endsWith Methods
- Java Initialize ArrayList
- Java Object Array Examples: For, Cast and getClass
- Java Objects, Objects.requireNonNull Example
- Java Optional Examples
- Java Static Initializer
- Java static Keyword
- Java Package: Import Keyword Example
- Java Do While Loop Examples
- Java Double Numbers: Double.BYTES and Double.SIZE
- Java Truncate Number: Cast Double to Int
- Java Padding: Pad Left and Right of Strings
- Java Anagram Example: HashMap and ArrayList
- Java Math.abs: Absolute Value
- Java Extends: Class Inheritance
- Java String Class
- Java String Switch Example: Switch Versus HashMap
- Java StringBuffer: append, Performance
- Java Array Examples
- Java Remove Duplicates From ArrayList
- Java if, else if, else Statements
- Java Math.ceil Method
- Java This Keyword
- Java PriorityQueue Example (add, peek and poll)
- Java Process.start EXE: ProcessBuilder Examples
- Java Palindrome Method
- Java parseInt: Convert String to Int
- Java toCharArray: Convert String to Array
- Java Caesar Cipher
- Java Array Length: Get Size of Array
- Java String Array Examples
- Java String compareTo, compareToIgnoreCase
- Java String Concat: Append and Combine Strings
- Java Cast and Convert Types
- Java Math.floor Method, floorDiv and floorMod
- Java Math Class: java.lang.Math
- Java While Loop Examples
- Java Reverse String
- Java Download Web Pages: URL and openStream
- Java Math.pow Method
- Java Math.round Method
- Java Right String Part
- Java MongoDB Example
- Java Substring Examples, subSequence
- Java Prime Number Method
- Java Sum Methods: IntStream and reduce
- Java switch Examples
- Java Convert HashMap to ArrayList
- Java Remove Duplicate Chars
- Java Constructor: Overloaded, Default, This Constructors
- Java String isEmpty Method (Null, Empty Strings)
- Java Regex Examples (Pattern.matches)
- Java ROT13 Method
- Java Random Number Examples
- Java Recursion Example: Count Change
- Java reflect: getDeclaredMethod, invoke
- Java Count Letter Frequencies
- Java ImmutableList Examples
- Java String equals, equalsIgnoreCase and contentEquals
- Java valueOf and copyValueOf String Examples
- Java Vector Examples
- Java Word Count Methods: Split and For Loop
- Java Tutorial | Learn Java Programming
- Java toLowerCase, toUpperCase Examples
- Java Ternary Operator
- Java Tree: HashMap and Strings Example
- Java TreeMap Examples
- Java while loop
- Java Convert String to Byte Array
- Java Join Strings: String.join Method
- Java Modulo Operator Examples
- Java Integer.MAX VALUE, MIN and SIZE
- Java Lambda Expressions
- Java lastIndexOf Examples
- Java Multiple Return Values
- Java String.format Examples: Numbers and Strings
- Java Joiner Examples: join
- Java Keywords
- Java Replace Strings: replaceFirst and replaceAll
- Java return Examples
- Java Multithreading Interview Questions (2021)
- Java Collections Interview Questions (2021)
- Java Shuffle Arrays (Fisher Yates)
- Top 30 Java Design Patterns Interview Questions (2021)
- Java ListMultimap Examples
- Java String Occurrence Method: While Loop Method
- Java StringBuilder capacity
- Java Math.max and Math.min
- Java Factory Design Pattern
- Java StringBuilder Examples
- Java Mail Tutorial
- Java Swing Tutorial
- Java AWT Tutorial
- Java Fibonacci Sequence Examples
- Java StringTokenizer Example
- Java Method Examples: Instance and Static
- Java String Between, Before, After
- Java BitSet Examples
- Java System.gc, Runtime.getRuntime and freeMemory
- Java Character Examples
- Java Char Lookup Table
- Java BufferedWriter Examples: Write Strings to Text File
- Java Abstract Class
- Java Hashtable
- Java Math class with Methods
- Java Whitespace Methods
- Java Data Types
- Java Trim String Examples (Trim Start, End)
- Java Exceptions: try, catch and finally
- Java vs C#
- Java Float Numbers
- Java Truncate String
- Java Variables
- Java For Loop Examples
- Java Uppercase First Letter
- Java Inner Class
- Java Networking
- Java Keywords
- Java If else
- Java Switch
- Loops in Java | Java For Loop
- Java File: BufferedReader and FileReader
- Java Random Lowercase Letter
- Java Calendar Examples: Date and DateFormat
- Java Case Keyword
- Java Char Array
- Java ASCII Table
- Java IntStream.Range Example (Get Range of Numbers)
- Java length Example: Get Character Count
- Java Line Count for File
- Java Sort Examples: Arrays.sort, Comparable
- Java LinkedHashMap Example
- Java Split Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf