Java.lang.String.format() Method



The java.lang.String.format(String format, Object... args) method returns a formatted string using the specified format string and arguments.


Following is the declaration for java.lang.String.format() method

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


  • format − This is a format string.

  • args − This is the argument referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.

Return Value

This method returns a formatted string.


  • IllegalFormatException − If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.

  • NullPointerException − If the format is null.


The following example shows the usage of java.lang.String.format() method.

package com.tutorialspoint;

import java.lang.*;
import java.util.*;

public class StringDemo {

   public static void main(String[] args) {

      double piVal = Math.PI;
      /* returns a formatted string using the specified format
         string, and arguments */
      System.out.format("%f\n", piVal);

Let us compile and run the above program, this will produce the following result −