Skip to content
Related Articles

Related Articles

Java String format() with examples
  • Difficulty Level : Basic
  • Last Updated : 04 Dec, 2018

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

Signature:
There are two type of string format() method:

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

Parameter:

loc– locale value to be applied on the format() method
form– format of the output string
args– It specifies the number of arguments for the format string.It may be zero or more.



Return:

This method returns a formatted string.

Exception:

NullPointerException -If the format is null.
IllegalFormatException -If the format specified is illegal or there are insufficient arguments.

Example:To show working of format() method




// Java program to demonstrate
// working of format() method
  
class Gfg1 {
    public static void main(String args[])
    {
        String str = "GeeksforGeeks.";
  
        // Concatenation of two strings
        String gfg1 = String.format("My Company name is %s", str);
  
        // Output is given upto 8 decimal places
        String str2 = String.format("My answer is %.8f", 47.65734);
  
        // between "My answer is" and "47.65734000" there are 15 spaces
        String str3 = String.format("My answer is %15.8f", 47.65734);
  
        System.out.println(gfg1);
        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 program to demonstrate
// concatenation of arguments to the string
// using format() method
  
class Gfg2 {
    public static void main(String args[])
    {
        String str1 = "GFG";
        String str2 = "GeeksforGeeks";
  
        //%1$ represents first argument, %2$ second argument
        String gfg2 = String.format("My Company name"
                 " is: %1$s, %1$s and %2$s", str1, str2);
  
        System.out.println(gfg2);
    }
}


Output:

My Company name is: GFG, GFG and GeeksforGeeks




// Java program to show
// left padding using
// format() method
  
class Gfg3 {
    public static void main(String args[])
    {
        int num = 7044;
  
        // Output is 3 zero's("000") + "7044",
        // in total 7 digits
        String gfg3 = String.format("%07d", num);
  
        System.out.println(gfg3);
    }
}


Output:

0007044

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :