Java.lang.String.format() Method



Description

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

Declaration

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

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

Parameters

  • l − This is the locale to apply during formatting. If l is null then no localization is applied.

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

Exception

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

Example

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

package com.tutorialspoint;

import java.lang.*;

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);
      
      /* returns a formatted string using the specified locale, format
         string and arguments */
      System.out.format(Locale.US, "%10.2f", piVal);
   }
}

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

3.141593
3.14
java_lang_string.htm
Advertisements