Function Description
The Java String class format() method is used to get the formatted string. This method uses specified locale, format string, and arguments to return the formatted string. It is a static method of String class. In the String class, the format() method is defined as an overloaded method.
- One format() is defined without locale: To return a formatted string, this method uses specified format string and arguments. It uses the default locale returned by Locale.getDefault() method during formatting.
- Another format() is defined with locale: To return a formatted string, this method uses specified format string, arguments, and locale.
Method Signature
- format() without locale :
public static String format(String format, Object… args) - format() with locale
public static String format(Locale locale, String format, Object… args)
Parameters
locale: To apply localization during string formatting. If locale is null then no localization is applied.
format : A format string. Format specifies by
%c –Character
%s – String
%d – Integer
%f – Floating number
%o – Octal
%x – Hexadecimal
%h – hash code of a value
args: Arguments are referenced by the format specifiers in the format string. Arguments can be zero or more. If given arguments are more than format specifiers, then extra arguments are ignored
Return Type
A formatted String
Exception
Throws java.util.IllegalFormatException, if
- Format string contains illegal syntax
- A format specifier that is incompatible with the given arguments
- Insufficient arguments are given to the format string
- Or other illegal conditions
Examples of Java String Class format() Methods
- Example of Java String Class format() method without Locale
public class ExampleStringFormat { private void getStringFormat() { System.out.println("//format() method without specified locale "); String str = "to String format function learning."; int year = 2020; float discount = 10.458f; double price = 2678.566567d; // String formating for string String fomratStr1 = String.format("Welcome %s", str); // string formating for integer String fomratStr2 = String.format("Year is %d ", year); // string formating for decimal numbers round of to 2 decimal String fomratStr3 = String.format("Discount is %.2f", discount); // string formating for decimal number round of to 3 decimal String fomratStr4 = String.format("Price is %.3f ", price); System.out.println(fomratStr1); System.out.println(fomratStr2); System.out.println(fomratStr3); System.out.println(fomratStr4); } public static void main(String[] args) { ExampleStringFormat exampleStringFormat = new ExampleStringFormat(); exampleStringFormat.getStringFormat(); } } Output: //format() method without specified locale Welcome to String format function learning. Year is 2020 Discount is 10.46 Price is 2678.567
2. Example of Java String Class format() method with Locale
public class ExampleStringFormat { private void getStringFormatLocaleSpecific() { System.out.println("//Format function with locale "); String str = "to String Locale specific format function learning."; // String formating for string in US locale String fomratStr1 = String.format(Locale.US, "Welcome %s ", str); System.out.println(fomratStr1); } public static void main(String[] args) { ExampleStringFormat exampleStringFormat = new ExampleStringFormat(); exampleStringFormat.getStringFormatLocaleSpecific(); } } Output: //Format function with locale Welcome to String Locale specific format function learning.
3. Example of Java String Class format() method with Multiple Arguments
public class ExampleStringFormat { private void getStringFormatForMultipleArguments() { System.out.println("//Use of multiple arguments in a format function"); String str = "to String format function learning"; int year = 2020; float discount = 10.458f; double price = 2678.566567d; // use of multiple arguments in format function String fomratStr = String.format("Welcome %s in year %d with discount %.2f and price %.3f", str, year, discount, price); System.out.println(fomratStr); } public static void main(String[] args) { ExampleStringFormat exampleStringFormat = new ExampleStringFormat(); exampleStringFormat.getStringFormatForMultipleArguments(); } } Output: //Use of multiple arguments in a format function Welcome to String format function learning in year 2020 with discount 10.46 and price 2678.567
Other Methods of String Class
Sequence | Method | Description |
1 | char charAt(int index) | This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed. |
2 | int length() | Returns the number of characters count in a string. |
3 | String substring(int beginIndex) | Returns substring from the given index position to the end index of the string. |
4 | String substring(int beginIndex, int endIndex) | Returns substring from the specified begin index to the specified end index. |
5 | boolean contains(CharSequence s) | Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string. |
6 | static String join(CharSequence delimiter, CharSequence… elements) | Returns joined string. This method joins each passing String using the specified delimiter. It is a static method. |
7 | static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method. |
8 | boolean equals(Object another) | Returns boolean value(true/false). It checks the equality of string with the passing object. |
9 | boolean isEmpty() | Returns boolean value(true/false). It returns true if the string is empty otherwise returns false. |
10 | String concat(String str) | Returns the concatenating string. It concatenates the passing string at the end of the string. |
11 | String replace(char old, char new) | Return the replaced string. It replaces all occurrences of the specified character with the new character. |
12 | String replace(CharSequence old, CharSequence new) | Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence. |
13 | String replaceAll(String regex, String replacement) | Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression. |
14 | String replaceFirst(String regex, String replacement) | Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression. |
15 | static boolean equalsIgnoreCase(String another) | Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It compares the content irrespective of lowercase or uppercase of the character(s). |
16 | String[] split(String regex) | Returns the array of strings resulting from splitting of the string around matches of the given regular expression. String is breaked into strings from all the matching regular expressions. |
17 | String[] split(String regex, int limit) | Returns the array of strings resulting from splitting of the string around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit. |
18 | String intern() | Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison. |
19 | int indexOf(int ch) | Returns the index value of first occurrence of the specified character within the string |
20 | int indexOf(int ch, int fromIndex) | Returns the index value of first occurrence of the specified character from the substring starting from specified index |
21 | int indexOf(String substring) | Returns the index value of first occurrence of the specified substring within the string. |
22 | int indexOf(String substring, int fromIndex) | Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index. |
23 | int lastIndexOf(int ch) | Returns the index value of last occurrence of the specified character |
24 | int lastIndexOf (int ch, int fromIndex) | Returns the index value of last occurrence of the specified character, search starts at given fromIndex. |
25 | int lastIndexOf (String str) | Returns the index value of last occurrence of the specified string. |
26 | int lastIndexOf (String str, int fromIndex | Returns the index value of last occurrence of the specified string, searches start from given fromIndex |
27 | String toLowerCase() | Returns all the characters of the string in lowercase . |
28 | String toLowerCase(Locale l) | Returns all the characters of the string in lowercase using specified locale. |
29 | String toUpperCase() | Returns all the characters of the string in uppercase. |
30 | String toUpperCase(Locale l) | Returns all the characters of the string in uppercase using specified locale. |
31 | String trim() | Returns the string after removing the white space from the beginning and end of the string. |
32 | static String valueOf(int value) | Return the converted string. It converts the objects and all primitive types of values into string. It is a static method. |
In this article, we learned all about the format() method of String class with examples. Apart from the format() method, we got an idea about other String methods too. We will come up with more articles explaining other String methods. For more details please click on the respective methods link.