What is the String.format() method in Java?

The Java String.format() method returns the formatted string by a given locale, format, and argument.

If the locale is not specified in the String.format() method, it uses the default locale by calling the Locale.getDefault() method.

Types of String.Format()

There are two types of String.format() methods:

1. public static String format(Locale loc, String form, Object… args)

2. public static String format(String form, Object… args)

Parameters

  • loc: locale value to be applied on the format() method.

  • form: format of the output string.

  • args: specifies the number of arguments for the format string. It may be zero or more.

There is a format specifier used in the format() method that identifies the format of the return value.

svg viewer

Format specifiers

Format specifier Data type Output
%a floating point (except BigDecimal) returns Hex output of floating point number
%b Any type “true” if non-null, “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Hex string.

Code

The following code displays the output of the String.format() with a locale:

import java.util.Formatter;
import java.util.Locale;
class example {
public static void main(String[] args) {
// create a new formatter
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
// format a new string
String name = "Educative";
formatter.format(Locale.US,"My company's name is %s !"
, name);
// print the formatted string with specified locale
System.out.println("" + formatter + " "
+ formatter.locale());
}
}

The following code displays the output of the String.format() by concatenating two strings:

class example {
public static void main(String args[])
{
String str = "Educative";
// Concatenation of two strings
String s= String.format("My Company name is %s", str);
System.out.println(s);
}
}
Copyright ©2024 Educative, Inc. All rights reserved