Introduction
In Java, strings are objects representing a sequence of character values. An array of characters work the same as a string in Java. The Java String class has a lot of methods to perform operations on strings like compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring(), format(). In this article, we will learn about string format() with the help of code examples. Let us dive into the topic.
What is the String format() method?
The String format() method in java returns a formatted string using the given Locale, specified format string, and arguments. If the Locale is not specified in String.format() method, it uses the default locale by calling the Locale.getDefault() method. In addition to concatenating the strings, we can format the final concatenated string using this method. This format() method of java language is like the sprintf() function in the C Programming language.
Note: The Java Locale class object represents a specific geographic, cultural, or political region. It is a mechanism to for identifying objects, not a container for the objects themselves. A Locale object logically consists of the fields like languages, script, country, variant, extensions.
Syntax: These are two ways in which you can use the string format() method:
public static String format(Locale loc, String form, Object... args)
public static String format(String form, Object... args)
Parameters:
- The locale value to be applied to format()
- The format of the output.
- args specifying the number of arguments for the format string.
Return Type: Formatted string.
There are some exceptions thrown if:
1. If the format is null: NullPointerException
2. If the format is illegal or incompatible: IllegalFormatException
Example 1: Java program to demonstrate the working of format() method
class Ninja {
public static void main(String args[])
{
String str = "Rakesh";
// Concatenation of two strings
String s = String.format("My name is %s", str);
// Output is given upto 8 decimal places
String str2 = String.format("My internal assessment marks are %.8f", 18.5);
System.out.println(s);
System.out.println(str2);
}
}
Output
My name is Rakesh
My internal assessment marks are 18.50000000
Example 2: Java program to demonstrate concatenation of Arguments to the string using format() method
class Ninja {
public static void main(String args[])
{
String str1 = "Coding";
String str2 = "Ninjas";
// %1$ represents first argument
// %2$ second argument
String str = String.format("My Company name" + " is: %1$s %2$s", str1, str2);
System.out.println(str);
}
}
Output:
My Company name is: Coding Ninjas
Example 3: Java program to Illustrate Left Padding using format() method
class Ninja {
public static void main(String args[])
{
int num = 1536;
// The output will be 3 zero's + "1536" in total 7 digits
String str = String.format("%07d", num);
System.out.println(str);
}
}
Output:
0001536
Must Read Array of Objects in Java