Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Java String trim() Method
Next article icon

Java String format() Method

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the String.format() method allows us to create a formatted string using a specified format string and arguments. We can concatenate the strings using this method, and at the same time, we can format the output with options such as width, alignment, decimal places, and more.

Example: In the example below, we will use the String.format() method to concatenate a string and format the output with a placeholder.

Java
// Java program to demonstrate working of format() method class Geeks {     public static void main(String args[]) {                String s = "GeeksforGeeks";                  // Concatenate string          // using format()         String res = String.format("Welcome to %s!", s);          System.out.println(res);     } } 

Output
Welcome to GeeksforGeeks! 

Explanation: In the above example, the format() method of the String class is used to insert the value of “s” into the formatted string. The placeholder %s is replaced with the string value.

Table of Content

  • Syntax of format() Method
  • Examples of String format() Method
    • 1. Formatting Floating-Point Numbers
    • 2. Advanced Formatting with Decimal and Thousands Separator
    • 3. Complex Placeholder Formatting

Syntax of format() Method

There are two main versions of the format() method:

public static String format(Locale locale, String form, Object… args);

public static String format(String format, Object… args);

Parameters:

  • locale: The locale value to be applied (optional).
  • format: The format string that defines how the output should look.
  • args: The arguments to be formatted as per the format string.

Return Type: The method returns a formatted string.

Exceptions:

  • NullPointerException:If the format is null.
  • IllegalFormatException:If the format specified is illegal or there are insufficient arguments.

Examples of String format() Method

1. Formatting Floating-Point Numbers

Example: Using String.format() method to show concatinate the two floating values of given variable using %2f.

Java
// Java program to demonstrate floating-point  // formatting with format() class Geeks {     public static void main(String args[]) {                double d = 9876.54321;                  // Format the float number with          // 2 decimal places         String s = String.format("Formatted Value: %.2f", d);          System.out.println(s);     } } 

Output
Formatted Value: 9876.54 

Explanation: In this example, a floating-point number 9876.54321 is formatted to show only two decimal places using String.format(). The placeholder %.2f ensures that the value is rounded to two decimal places and displayed.

  • %2f: The f specifier is for floating-point numbers, and .2 means the number should be rounded to two decimal places.
  • The formatted value 9876.54 is printed with the label Formatted Value, by providing a more readable output.


2. Advanced Formatting with Decimal and Thousands Separator

In this example, we will specify the formatting options like grouping digits, for example, for large numbers and controlling the number of decimal places.

Example: Using String.format() method for advance formatting with decimal and thousands seperator.

Java
// Java program to demonstrate  // advanced formatting using format() method class Geeks {     public static void main(String args[]) {                // Define a double value          // representing a price         double d = 12345.6789;                  // Format the price with thousands          // separator and two decimal places         String s = String.format("%1$,10.2f", d);          System.out.println("Formatted Price: " + s);     } } 

Output
Formatted Price:  12,345.68 

Explanation: In the above example, it formats the floating-point number with a thousands separator and two decimal places. The number 12345.6789 is formatted to 12,345.68.

In the placeholder,

  • %1$: It refers to the first argument (d), the price value.
  • ,: It groups digits with a comma as a thousands separator.
  • 10.2f: It ensures that the floating-point number takes at least 10 characters, with 2 decimal places.

3. Complex Placeholder Formatting

In this example, we will combine multiple formatting components to customize how the arguments should appear.

Example: Using String.format() method with complex placeholder formatting.

Java
// Java program to demonstrate  // complex placeholder formatting class Geeks {     public static void main(String args[]) {          // Declare a double value          // representing the distance         double d = 1500.75;                // Declare a string value          // representing the unit of measurement         String s = "kilometers";          // Correct the argument order to match the format specifiers         String res = String.format("%1$,7.1f %2$s", d, s);          System.out.println(res);     } } 

Output
1,500.8 kilometers 

Explanation: In the above example, it formats a floating-point number and a string using placeholders in the String.format() method. The number 1500.75 is formatted with a comma separator and one decimal place, and the string “kilometers” is added next to it.

In the placeholder,

  • %2$: Refers to the second argument i.e. “d” the distance.
  • ,: Groups digits with a comma as a thousands separator.
  • 7.1f: This ensures that the floating-point number takes at least 7 characters in total, with 1 decimal place.
  • %1$s: It refers to the first argument i.e. “s” the unit and formats it as a string.

Java Format Specifiers

The String.format() method uses format specifiers to format various types of data. Below are some common specifiers:

Format Specifier

Data TypeOutput or Return value

%a

floating point                       Returns a Hex output of floating point number

%b

any typeTrue or False

%c

characterUnicode character

%d

integer Decimal Integer

%e

floating pointa decimal number in scientific notation

%f

floating pointdecimal number

%g

floating pointdecimal number, possibly in scientific notation depending on the precision and value    

%h

any typeHex String of value from hashCode() method

%n

NonePlatform-specific line separator

%o

integer Octal number

%s

any typeString value

%t

Date/Time %t is the prefix for Date/Time conversions.

%x

integerHex string


Next Article
Java String trim() Method

N

Niraj_Pandey
Improve
Article Tags :
  • DSA
  • Java
  • Java-Functions
  • Java-Strings
Practice Tags :
  • Java
  • Java-Strings

Similar Reads

  • YearMonth format() method in Java
    The format() method of YearMonth class in Java is used to format this YearMonth instance according to a specified DateTimeFormatter for year-month passed as parameter to this method. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a single parameter formatter
    1 min read
  • Java String trim() Method
    The trim() method of the String class in Java is used to remove leading and trailing whitespace from a string. The Unicode value of the space character is "\u0020". It does not remove any whitespace in the middle of the string. This method returns a new string with the whitespace removed and leaves
    4 min read
  • DecimalFormat setGroupingSize() method in Java
    The setGroupingSize() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to set the grouping size for this DecimalFormat instance or not. The grouping size is the number of integers in each group in the integral part of a decimal number. For example, the grouping si
    2 min read
  • JavaTuples toString() method
    The toString() method in org.javatuples is used to convert the values in TupleClass into a String. This method is inherited from the JavaTuple class. This method can be used to any tuple class object of javatuples library. It returns a String value formed with the values in the TupleClassObject. Met
    2 min read
  • Java String valueOf() Method
    The valueOf() method of the String class in Java helps to convert various data types like integers, floats, booleans, and objects into their string representations. It makes it simple to work with string manipulation, logging, and displaying data efficiently. Example: To convert a number into text f
    3 min read
  • DecimalFormat toPattern() method in Java
    The toPattern() method of the DecimalFormat class in Java is used to convert the format of the current pattern of this DecimalFormat to a string format. This converted string represents the pattern which is used to format the current state of this DecimalFormat instance. Syntax: public String toPatt
    2 min read
  • Object toString() Method in Java
    Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class, henceforth, it is a child of the Object class. If a class does not extend any other class then it is a direct child class of Object, and if it extends another class, then it is
    3 min read
  • StringBuilder append() Method in Java
    In Java, the append() method of StringBuilder class is used to add data to the end of an existing StringBuilder object. It supports appending different data types like strings, integers, characters, and booleans by making it easy for dynamic string manipulation. Example 1: Here, we use the append()
    4 min read
  • DecimalFormat setMultiplier() method in Java
    The setMultiplier() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to a multiplier value to be used with this DecimalFormat instance. This multiplier value can be used while working with percent, percentile etc. For Example, for a multiplier value 10, the number
    1 min read
  • Year format() method in Java with Examples
    The format() method of Year class in Java is used to format the current Year object according to the DateTimeFormatter passed to it as a parameter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a single parameter formatter. It specifies a DateTimeFormatter
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences