How to use String.format() in Java?

JavaServer Side ProgrammingProgramming

The format() method of the java.lang.String class accepts a format string and an array of arguments and the string in specified format.

Example

Following example formats a date using the format() method −

Live Demo

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test {
   public static void main(String args[]){    
      //Instantiating the GregorianCalendar  
      Calendar cal = GregorianCalendar.getInstance();
      System.out.println("Date: "+cal.get(Calendar.DATE));
      System.out.println("Month: "+cal.get(Calendar.MONTH));
      System.out.println("Year: "+cal.get(Calendar.YEAR));    
      Object arr[] = { "Date", cal };
      System.out.println("Desired Format: ");
      System.out.println(String.format("%1$s = %2$tY %2$tm %2$te", arr));
   }
}

Output

Date: 7
Month: 10
Year: 2020
Desired Format:
Date = 2020 11 7

Example

In the following example we are trying to print an integer with additional zeros using the format() method.

Live Demo

public class Demo {
   public static void main(String []args){
      int val = 1254;
      String str = String.format("%07d", val);
      System.out.println(str);
   }
}

Output

0001254

Example

Following example demonstrates the format strings for all the data types −

Live Demo

public class Demo {
   public static void main(String []args){
      String str = String.format("%d", 245);
      System.out.println(str);
      str = String.format("%s", "Welcome to Tutorialspoint");
      System.out.println(str);
      str = String.format("%f", 126.54);
      System.out.println(str);
      str = String.format("%c", 't');
      System.out.println(str);
   }
}

Output

245
Welcome to Tutorialspoint
126.540000
t
raja
Published on 06-Feb-2021 03:57:48
Advertisements