How to Format Strings in Java



String formatting is the process of modifying the output of a string to a specific format, like placeholders for variables, text alignment, and formatting numerical values. The following are the methods in Java using the format() method, which allows for a more accurate approach to presenting values in the output.

Using the string format() method

The string format() method method allows for formatting strings, integers, and decimal values using different format specifiers. This method returns a formatted string based on the specified locale, formatter, and arguments, and if no locale is given, the default is used. The String.format() is a static method of the Java String class.

Syntax

The following is the syntax for Java String format() method

public static String format(Locale l, String format, Object... args) //first syntax
public static String format(String format, Object... args) // second syntax

Example 1

The following example returns a formatted string value using a specific locale, format, and arguments in the format() method

import java.util.*;

public class StringFormat{
   public static void main(String[] args){
      double e = Math.E;
      System.out.format("%f%n", e);
      System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
   }
}

Output

2.718282
2,7183   

Example 2

The following is another example of format strings

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        
java_strings.htm
Advertisements