Java String format() Method With Examples
Last Updated :
04 Jun, 2023
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 format(Locale loc, String form, Object... args)
public static String format(String form, Object... args)
Parameters
locale: the locale value to be applied on the format() method
format: The format of the output string.
args: args specifying the number of arguments for the format string. It may be zero or more.
Return Value
Exception Thrown
Example of Java String format()
Java
class GFG {
public static void main(String args[])
{
String str = "GeeksforGeeks" ;
String s
= String.format( "My Company name is %s" , str);
String str2
= String.format( "My answer is %.8f" , 47.65734 );
String str3 = String.format( "My answer is %15.8f" ,
47.65734 );
System.out.println(s);
System.out.println(str2);
System.out.println(str3);
}
}
|
Output
My Company name is GeeksforGeeks
My answer is 47.65734000
My answer is 47.65734000
Java Format Specifiers
Format Specifier
|
Data Type |
Output or Return value |
%a
|
floating point |
Returns a Hex output of floating point number |
%b
|
Any type |
True or False |
%c
|
character |
Unicode character |
%d
|
integer |
Decimal Integer |
%e
|
floating point |
a 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 |
Octal number |
%s
|
Any type |
String value |
%t
|
Date/Time |
%t is the prefix for Date/Time conversions. |
%x
|
integer |
Hex string |
Examples of Java String Format Specifiers
Example 1
Java
class GFG {
public static void main(String args[])
{
String str1 = "GFG" ;
String str2 = "GeeksforGeeks" ;
String str = String.format(
"My Company name"
+ " is: %1$s, %1$s and %2$s" ,
str1, str2);
System.out.println(str);
}
}
|
Output
My Company name is: GFG, GFG and GeeksforGeeks
Example 2
Java
class GFG {
public static void main(String args[])
{
int num = 7044 ;
String str = String.format( "%07d" , num);
System.out.println(str);
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...