Java String format() method example.

Java 8Object Oriented ProgrammingProgramming

Java provides printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of −

System.out.printf("The value of the float variable is " +
   "%f, while the value of the integer " +
   "variable is %d, and the string " +
   "is %s", floatVar, intVar, stringVar);

You can write −

String fs;
fs = String.format("The value of the float variable is " +
   "%f, while the value of the integer " +
   "variable is %d, and the string " +
   "is %s", floatVar, intVar, stringVar);
   System.out.println(fs);

Example

Following example returns a formatted string value by using a specific locale, format, and arguments in format() method.

Live Demo

public class HelloWorld {
   public static void main(String []args) {
      String name = "Hello World";
      String s1 = String.format("name %s", name);
      String s2 = String.format("value %f",32.33434);
      String s3 = String.format("value %32.12f",32.33434);

      System.out.print(s1);
      System.out.print("\n");
      System.out.print(s2);
      System.out.print("\n");
      System.out.print(s3);
      System.out.print("\n");
   }
}

Output

name Hello World
value 32.334340
value 32.334340000000
raja
Published on 12-Feb-2018 10:41:55
Advertisements