How to Use Java String Class format() Method

String format() Method

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.

  1.  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.

  2.  Another format() is defined with locale: To return a formatted string, this method uses specified format string, arguments, and locale.

Method  Signature

  1. format() without locale :

    public static String format(String format, Object… args)

  2. 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

  1. 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

SequenceMethodDescription
1char 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.
2int length()Returns the number of characters count  in  a string.
3String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
4String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
5boolean 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.
6static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
7static 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.
8boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
9boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
10String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
11String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
12String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
13String 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.
14String 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.
15static 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).
16String[] 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.
17String[] 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.
18String 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.
19int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
20int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
21int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
22int 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.
23int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
24int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
25int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
26int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
27String toLowerCase()Returns all the characters of the string in lowercase .
28String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
29String toUpperCase()Returns all the characters of the string in uppercase.
30String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
31String trim()Returns the string after removing the white space from the beginning and end of the string.
32static 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.

Leave a Reply

Your email address will not be published. Required fields are marked *