Open In App

Format Specifiers in Java

Last Updated : 17 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Format specifiers begin with a percent character (%) and terminate with a “type character, ” which indicates the type of data (int, float, etc.) that will be converted the basic manner in which the data will be represented (decimal, hexadecimal, etc.) The general syntax of a format specifier is

% [flags] [width] [.precision] [argsize] typechar

The format() method of Formatter class accepts a wide variety of format specifiers. When an uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper- and lowercase specifiers perform the same conversion. 
 

Format Specifier Conversion Applied
%% Inserts a % sign
%x %X Integer hexadecimal
%t %T Time and Date
%s %S String
%n Inserts a newline character
%o Octal integer
%f Decimal floating-point
%e %E Scientific notation
%g Causes Formatter to use either %f or %e, whichever is shorter
%h %H Hash code of the argument
%d Decimal integer
%c Character
%b %B Boolean
%a %A Floating-point hexadecimal
  • Space format specifier : When creating columns of numbers, it is sometimes very useful to print a space before a positive number so that positive and negative number get aligned. To do this, space format specifier can be used. Syntax:
Formatter().format("% d", -111);
Formatter().format("% d", 111);

Output:
-111
 111

Example: 

JAVA




// Java program to demonstrate
// the space format specifier
 
import java.util.*;
 
class GFG {
    public static void main(String args[])
    {
 
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // Use Space format specifier
        formatter.format("%d", -111);
        System.out.println(formatter);
 
        formatter = new Formatter();
        formatter.format("% d", 111);
        System.out.println(formatter);
 
        formatter = new Formatter();
        formatter.format("% d", -222);
        System.out.println(formatter);
 
        formatter = new Formatter();
        formatter.format("% d", 222);
        System.out.println(formatter);
    }
}


Output:

-111
 111
-222
 222
  • + Sign Specifier: This adds the + sign before positive numeric value, and has no effect on negative numeric value. Syntax:
Formatter().format("%+d", 111);

Output:
+111

Example: 

JAVA




// Java program to demonstrate
// the + sign Specifier format specifiers.
 
import java.util.*;
 
class GFG {
    public static void main(String args[])
    {
 
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // + sign specifier
        formatter = new Formatter();
        formatter.format("%+d", 111);
        System.out.println(formatter);
 
        // + sign specifier
        // on - sign, it will have no effect
        formatter = new Formatter();
        formatter.format("%+d", -111);
        System.out.println(formatter);
    }
}


Output:

+111
-111
  • ( specifier: This specifier puts the negative numeric values inside the parentheses, and has no effect on the positive numeric values. Syntax:
Formatter().format("%(d", -111);
Formatter().format("%(d", 111);

Output:
(111)
111

Example: 

JAVA




// Java program to demonstrate
// the ( Specifiers format specifiers.
 
import java.util.*;
 
class GFG {
    public static void main(String args[])
    {
 
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // ( Specifier
        formatter = new Formatter();
        formatter.format("%(d", -111);
        System.out.println(formatter);
 
        formatter = new Formatter();
        formatter.format("%(d", 111);
        System.out.println(formatter);
    }
}


Output:

(111)
111
  • Comma, Specifier: For displaying large numbers, it is often useful to add grouping separators by comma (, ). For example, the value is 1000000 more easily read when formatted as 1, 000, 000. To add grouping specifiers (, ) use the comma(, ) Specifier. Syntax:
Formatter().format("%, d", 1000000);

Output:
1, 000, 000

Example: 

JAVA




// Java program to demonstrate
// the comma format specifiers.
 
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
 
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // comma Specifier
        formatter = new Formatter();
        formatter.format("%, d", 1000000);
        System.out.println(formatter);
 
        // comma Specifier
        formatter = new Formatter();
        formatter.format("%, .3f", 32659526566.4521);
        System.out.println(formatter);
    }
}


Output:

1, 000, 000
32, 659, 526, 566.452
  • Left Justification(-) Specifier: By default all output is right-shifted. That is, if the field width is longer than the data printed, data will be placed on the right side of the field. One can force output to be left-justified by placing a minus sign directly after the %. For instance, %-20.4f left justifies a floating-point number with two decimal places in a 20-character field. Syntax:
Formatter().format("|%-20.4f|", 1234.1234);

Output:
|           1234.1234|
|1234.1234           |

Example: 

JAVA




// Java program to demonstrate
// the left justification format specifiers.
 
import java.util.*;
 
class GFG {
    public static void main(String args[])
    {
 
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // right justify by default
        formatter = new Formatter();
        formatter.format("|%20.4f|", 1234.1234);
        System.out.println(formatter);
 
        // left justify
        formatter = new Formatter();
        formatter.format("|%-20.4f|", 1234.1234);
        System.out.println(formatter);
    }
}


Output:

|           1234.1234|
|1234.1234           |
  • The %n format specifiers: The %n format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %n inserts a newline. It can’t be entered directly into the format string. 

JAVA




// Java program to demonstrate
// the newline %n format specifiers.
 
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // newline format specifier
        formatter.format("Geeks %nFor %nGeeks");
 
        // Print the output
        System.out.println(formatter);
    }
}


Output:

Geeks 
For 
Geeks
  • The %% format specifiers: The %% format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %% inserts a % sign. It can’t be entered directly into the format string. 

JAVA




// Java program to demonstrate
// the %% format specifiers.
 
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // %% format specifier
        formatter.format("10 %% 4 = 2");
 
        // Print the output
        System.out.println(formatter);
    }
}


Output:

10 % 4 = 2
  • The %x %X format specifiers: The %x or %X format specifier is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets. 

JAVA




// Java program to demonstrate
// the integer-Hexadecimal %x and %X
// format specifiers.
 
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // %x format specifier
        // It prints the number in Hexadecimal
        // with lowercase alphabets
        formatter.format("%x", 250);
 
        // Print the output
        System.out.println("LowerCase Hexadecimal"
                           + " using %x: "
                           + formatter);
 
        // %X format specifier
        // It prints the number in Hexadecimal
        // with uppercase alphabets
        formatter = new Formatter();
        formatter.format("%X", 250);
 
        // Print the output
        System.out.println("UpperCase Hexadecimal"
                           + " using %X: "
                           + formatter);
    }
}


Output:

LowerCase Hexadecimal using %x: fa
UpperCase Hexadecimal using %X: FA
  • The %e %E format specifiers: The %e or %E format specifier  is used to represent the Scientific Notation of a value. %e displays the Scientific Notation with lowercase alphabets whereas the %E specifier displays the Scientific Notation with uppercase alphabets. 

JAVA




// Java program to demonstrate
// the Scientific Notation %e and %E
// format specifiers.
 
import java.util.*;
 
public class GFG {
    public static void main(String args[])
    {
        // create Formatter class object
        Formatter formatter = new Formatter();
 
        // %e format specifier
        // It prints the number in Scientific Notation
        // with lowercase alphabets
        formatter.format("%e", 123.1234);
 
        // Print the output
        System.out.println("LowerCase Scientific Notation"
                           + " using %e: "
                           + formatter);
 
        // %E format specifier
        // It prints the number in Scientific Notation
        // with uppercase alphabets
        formatter = new Formatter();
        formatter.format("%E", 123.1234);
 
        // Print the output
        System.out.println("UpperCase Scientific Notation"
                           + " using %E: "
                           + formatter);
    }
}


Output:

LowerCase Scientific Notation using %e: 1.231234e+02
UpperCase Scientific Notation using %E: 1.231234E+02
  • Precision Formats A precision specifier can be applied to the %f, %e, %g, and %s format specifiers. 

JAVA




// Java program to demonstrate
// Precision Format specifiers
 
import java.util.Formatter;
 
public class GFG {
    public static void main(String args[])
    {
 
        // Create the Formatter instance
        Formatter formatter = new Formatter();
 
        // added floating-point data
        // using the %f or %e specifiers,
        // Format to 2 decimal places
        // in a 16 character field.
        formatter = new Formatter();
        formatter.format("%16.2e", 123.1234567);
        System.out.println("Scientific notation to 2 places: "
                           + formatter);
 
        // Format 4 decimal places.
        formatter = new Formatter();
        formatter.format("%.4f", 123.1234567);
        System.out.println("Decimal floating-point"
                           + " notation to 4 places: "
                           + formatter);
 
        // Format 4 places.
        // The %g format specifier causes Formatter
        // to use either %f or %e, whichever is shorter
        formatter = new Formatter();
        formatter.format("%.4g", 123.1234567);
        System.out.println("Scientific or Decimal floating-point "
                           + "notation to 4 places: "
                           + formatter);
 
        // Display at most 15 characters in a string.
        formatter = new Formatter();
        formatter.format("%.15s", "12345678901234567890");
        System.out.println("String notation to 15 places: "
                           + formatter);
 
        // Format into 10 digit
        formatter = new Formatter();
        formatter.format("%010d", 88);
        System.out.println("value in 10 digits: "
                           + formatter);
    }
}


Output:

Scientific notation to 2 places:         1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088

Related Article : Format Specifiers in C



Similar Reads

java.time.format.DecimalStyle Class in Java
java.time.format.DecimalStyle class acts as a central point for accessing the information. A significant part of handling dates and times is that localization. This class provides localized decimal style utilized in date and time formatting. Clone, finalize, getClass, notify, notifyAll, wait, are the methods that are declared in this class. Syntax:
2 min read
java.time.format.DateTimeFormatterBuilder Class in Java
DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects. DateTimeFormatterBuilder allows a DateTimeFormatter to be created. It is used for constructing formatters which are then used to print or parse. The formatters are built
6 min read
Java String format() Method With Examples
In Java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax of String format() There are two types of string format() methods mentioned below: public static String
3 min read
Program to Convert Milliseconds to a Date Format in Java
Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date that Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which c
2 min read
LocalDateTime format() method in Java
The format() method of LocalDateTime class in Java formats this date-time using the specified formatter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter formatter which specifies the formatter to use, not null. Returns: The function returns the formatted date string and not null. Below programs i
2 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 according to which the current Year object will be
2 min read
LocalDate format() method in Java
The format() method of LocalDate class in Java method formats this date using the specified formatter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter obj which specifies the formatter to be used and it is not null. Exceptions: The function throws only DateTimeException which occurs during an err
2 min read
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 which is the DateTimeFormatter according to which
1 min read
LocalTime format() method in Java with Examples
The format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string. Syntax: public String format(DateTimeFormatter formatter) Parameters: This method accepts a single parameter formatter which is the specified formatter. It sho
2 min read
MonthDay format() method in Java with Examples
The format() method of MonthDay class in Java formats this month-day using the specified formatter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter formatter which specifies the formatter to use and it is not null. Returns: The function returns the formatted date string and not null. Below progra
1 min read
OffsetDateTime format() method in Java with examples
The format() method of OffsetDateTime class in Java formats this date-time using the specified formatter. Syntax : public String format(DateTimeFormatter formatter) Parameter : This method accepts a single parameter formatter which specifies the formatter to use, not null.Return Value: It returns the formatted date string, not null.Exceptions: The
1 min read
OffsetTime format() method in Java with examples
The format() method of OffsetTime class in Java formats this time using the specified formatter which is passed in the parameter of the function. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a single mandatory parameter formatter which specifies the formatter to be used and it is not null. Return Value: I
2 min read
ZonedDateTime format() method in Java with Examples
The format() method of ZonedDateTime class in Java is used to format this date-time using the specified formatter passed as parameter.This date-time will be passed to the formatter to produce a string. Syntax: public String format(DateTimeFormatter formatter) Parameters: This method accepts a single parameter formatter which represents the formatte
2 min read
PrintWriter format(String, Object) method in Java with Examples
The format(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintWriter format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream format(String, Object) method in Java with Examples
The format(String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
SimpleDateFormat format() Method in Java with Examples
The format() Method of SimpleDateFormat class is used to format a given date into Date/Time string. Basically the method is used to convert this date and time into a particular format for say mm/dd/yyyy.Syntax: public final String format(Date date) Parameters: The method takes one parameter date of Date object type and refers to the date whose stri
2 min read
DateFormat format(Date obj) method in Java
The format() method of DateFormat class in Java is used to format a given Date object into a string representing Date/Time.Syntax: String format(Date date) Parameters: This method accepts a single parameter date which is a Date object. Return Value: This method returns a String which is the formatted date-time value of the Date object passed as a p
2 min read
DateFormat format() Method in Java with Examples
DateFormat class present inside java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time. DateFormat class extends Format class that means it is a subclass of Form
2 min read
ChronoLocalDate format() method in Java with Examples
The format() method of ChronoLocalDate interface in Java method formats this date using the specified formatter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter obj which specifies the formatter to be used and it is not null. Exceptions: The function throws only DateTimeException which occurs dur
2 min read
ChronoZonedDateTime format() method in Java with Examples
The format() method of ChronoZonedDateTime interface in Java is used to format this date-time using the specified formatter passed as parameter.This date-time will be passed to the formatter to produce a string. Syntax: default String format(DateTimeFormatter formatter) Parameters: This method accepts a single parameter formatter which represents t
2 min read
ChronoLocalDateTime format() method in Java with Examples
The format() method of ChronoLocalDateTime interface in Java formats this date-time using the specified formatter. Syntax: default String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter formatter which specifies the DateTimeFormatter to use, not null. Returns: The function returns the formatted date string and not nul
2 min read
ChoiceFormat format() method in Java with Examples
The format() method of java.text.ChoiceFormat class is used to get the appended string builder of the format value of particular limit value passed as parameter and text passed as parameter in this method. Syntax: public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition status) Parameter: This method takes the following para
2 min read
MessageFormat format() method in Java with Example : Set - 1
The format() method of java.text.MessageFormat class is used to get the formatted array of object appended into the string buffer object. formatted array will contain all forms of element lies in the pattern of MessageFormat object.Syntax: public final StringBuffer format(Object[] arguments, StringBuffer result, FieldPosition pos) Parameter: argume
3 min read
MessageFormat format() method in Java with Example : Set - 2
The format() method of java.text.MessageFormat class is used to get the formatted array of object according to the specified pattern of message format object. new string pattern will be considered while performing the action.Syntax: public static String format(String pattern, Object... arguments) Parameter: This method takes following argument as a
2 min read
Console format(String, Object) method in Java with Examples
The format(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. Syntax: public Console format(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It represents the format of the string. args - It repre
2 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read
How to Create Different Data Format of Cells in a Spreadsheet Using Java?
Formatting in excel is a neat trick in excel which is used to change the appearance of the data represented in the worksheet, formatting can be done in multiple ways such as we can format the data of the cells by using the styles. By default, all worksheet cells are formatted with the General number format. With the General format, anything you typ
4 min read
Compressing and Decompressing files using GZIP Format in java
The java.util.zip package provides classes compress and decompress the file contents. FileInputStream, FileOutputStream and GZIPOutputStream classes are provided in Java to compress and decompress the files. Compressing a File using GZIPOutputStream Methods used in the program read(): Reads a byte of data. Present in FileInputStream. int read() wri
2 min read