Java String format() Method With Examples

The format() method in Java is a versatile tool for creating formatted strings, allowing developers to control the presentation of data by incorporating specified formatting rules, locales, and input arguments.

You will learn to combine the format() method with various format specifiers to customise numeric, string, and date representations. Additionally, you will also learn how to specify locales to allow for the adaptation of formatting conventions to cater to diverse regional preferences.

What is format() in Java?

The format() method in Java returns a formatted string based on the provided locale, format, and arguments. When the locale is not explicitly specified in the String.format() method, the default locale is utilized, determined through the Locale.getDefault() method.

The functionality of the format() method in Java is similar to the sprintf() function in the C language and the printf() method in Java. This method creates formatted strings by incorporating specified formatting rules, locale settings, and input arguments. In cases where the locale is not explicitly set, the default locale ensures compatibility with the language’s localization settings.

What is the syntax of format() in Java?

There are 2 syntaxes, or types of string format() methods in Java; let us look at both of them and then understand their parameters and return types.

Below are the 2 types of the format() method:

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

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

The String.format() method in Java accepts three parameters. The first parameter, l, denotes the locale to be applied during the formatting process. No localisation is applied if this parameter is null and the formatting adheres to the default settings. The second parameter, format, represents the format string that defines the desired structure and placeholders for the arguments.

Lastly, the args parameter corresponds to the arguments referenced by the format specifiers in the format string. If the number of arguments exceeds the number of format specifiers, the surplus arguments are disregarded. The method accommodates various arguments, which may even be zero. The return value of this method is a formatted string incorporating the specified locale, format string, and arguments.

Format specifiers to be used with the format() method

Before we proceed further and look at some codes on how to use the string format() method, let us look at the different format specifiers that are supported by the String class in Java.

No Format Specifier Data Type Output
1 %a float Hex code
2 %b Any type True/False
3 %c char Unicode Character
4 %d Int (byte, short, long) Integer
5 %e float Decimal number
6 %f float Decimal number
7 %g float Decimal number
8 %h Any type Hex String
9 %n none Line separator
10 %o Int (byte, short, long) Octal Number
11 %s Any type String
12 %t Date/Time Date/Time
13 %x Int (byte, short, long) Hex String

Now that we know the theory of the string format() method in Java, let us implement all this knowledge and look at some programs utilizing the format() method.

class Main 
{
  public static void main(String[] args)
  {
    String language = "FirstCode";
    int number = 30;
    System.out.println(String.format("String: %s", language));  
    System.out.println(String.format("Hexadecimal Number: %x", number));
  }
}

Output:

String: FirstCode
Hexadecimal Number: 1e

The code above demonstrates using the String.format() method to create formatted strings. In the main method, a String variable named language is assigned the value “FirstCode,” and an int variable number is set to 30. Two System.out.println statements utilize the String.format() method to construct formatted strings.

The first statement uses the format specifier %s to include the value of the language variable in a string, resulting in the output “String: FirstCode.” The second statement employs the format specifier %x to represent the number variable in hexadecimal form, yielding the output “Hexadecimal Number: 1e.”

Formatting numbers using starting format()

class FirstCode 
{
  public static void main(String[] args) 
  {
    int n1 = 47;
    float n2 = 35.864f;
    double n3 = 44534345.76d;
    System.out.println(String.format("47 in octal: %o", n1));
    System.out.println(String.format("47 in hexadecimal: %x", n1));  
    System.out.println(String.format("35.864f in hexadecimal: %X", n1)); 
    System.out.println(String.format("47 as string: %s", n1));  
    System.out.println(String.format("35.864f as string: %s", n2)); 
    System.out.println(String.format("44534345.76d in scientific notation: %g", n3)); 
  }
}

Output:

47 in octal: 57
47 in hexadecimal: 2f
35.864f in hexadecimal: 2F
47 as string: 47
35.864f as string: 35.86444534345.76d in scientific notation: 4.45343e+07

The code above initializes three numeric variables (n1, n2, and n3) with values of 47, 35.864f, and 44534345.76d, respectively. The code utilizes the String.format() method to create formatted strings, and the System.out.println() statements are used to print the results.

The first three System.out.println() statements demonstrate the formatting of integer and floating-point values in different bases. The %o specifier represents the value of n1 in octal form, %x in hexadecimal form, and %X in uppercase hexadecimal for n2.

The next two statements showcase the %s specifier to represent numeric values as strings. In the fourth statement, the integer value of n1 is formatted as a string, and in the fifth statement, the floating-point value of n2 is represented as a string.

Lastly, the sixth statement uses the %g specifier to present the double value of n3 in scientific notation. However, there is a mistake in the code as it combines the value n3 with the subsequent string, resulting in a partially incorrect output.

Using multiple format specifier with string format()

class Main 
{
  public static void main(String[] args) 
  {
    int n1 = 47;
    String text = "FirstCode";
    System.out.println(String.format("%s\nhexadecimal: %x", text, n1));
  }
}

Output:

FirstCode
hexadecimal: 2f

The code above initializes an integer variable n1 with the value 47 and a string variable text with “FirstCode.” The String.format() method is used within a System.out.println() statement to create a formatted string. The format string includes two placeholders: %s for the string variable text and %x to represent the integer variable n1 in hexadecimal form.

The output displays the formatted string, a combination of “FirstCode” and the hexadecimal representation of the integer value 47. Therefore, the output reads as “FirstCode” on one line and “hexadecimal: 2f” on the next line. The %s specifier is replaced with the value of the string variable, and %x is replaced with the hexadecimal representation of the integer variable.

Using format() to pad numbers with spaces and 0

class Main 
{
  public static void main(String[] args) 
  {
    int num1 = 46, num2 = -46;
    System.out.println(String.format("|%5d|", num1));
    System.out.println(String.format("|%05d|", num1));
    System.out.println(String.format("%+d", num1));
    System.out.println(String.format("%+d", num2));
    System.out.println(String.format("%(d", num2));
  }
}

Output:

| 46|
|00046|
+46
-46
(46)

The java code above contains two integer variables, n1 and n2, initialized with values 46 and -46, respectively. The System.out.println() statements employ the String.format() method to create formatted strings, and the output demonstrates different formatting options.

The first print statement uses %5d to represent the value of n1 in a field of width 5, resulting in the output “| 46|”, where spaces are added to the left to achieve the specified width. The second print statement uses %05d to represent the value of n1 with zero-padding to the left, producing “|00046|”.

The third print statement utilizes %+d to include a sign for positive numbers, resulting in “+46” for n1. The fourth print statement also uses %+d for n2, displaying “-46” with the sign for negative numbers. The fifth print statement employs %(d to enclose negative numbers in parentheses, resulting in “(46)” for n2.

Using format() to print “0x” and “0” before hexadecimal and octal

class FirstCode
{
  public static void main(String[] args) 
  {
    int n = 47;
    System.out.println(String.format("%#o", n));
    System.out.println(String.format("%#x", n));
  }
}

Output:

057
0x2f

The code shown above initializes an integer variable n with the value 47. The System.out.println() statements use the String.format() method to create formatted strings with octal and hexadecimal representations of the integer value.

The first System.out.println() statement uses the format specifier %#o to represent the integer value n in octal form. The # flag is employed to include the “0” prefix, resulting in the output “057,” where the “0” indicates that the number is in octal notation.

The second System.out.println() statement uses %#x to represent the integer value n in hexadecimal form. Again, the # flag is used to include the “0x” prefix, resulting in the output “0x2f,” where the “0x” denotes that the number is in hexadecimal notation.

Specifying local while using format()

import java.util.Locale;
class Main
{
  public static void main(String[] args) 
  {
    int number = 54867593;
    System.out.println(String.format("Number: %,d", number));
    System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
  }
}

Output:

Number: 54,867,593
Number in German: 54.867.593

The code shown above initializes an integer variable number with the value 54867593. The code utilizes the String.format() method to create formatted strings representing the integer value with comma-separated thousands.

The first System.out.println() statement uses the format specifier %d and % to format the integer value number with comma-separated thousands. The output is “Number: 54,867,593,” where commas are inserted to improve readability for large numbers.

The second System.out.println() statement demonstrates the influence of locale on formatting. It uses String.format() with the Locale.GERMAN parameter to format the integer value number in German style, where periods are used as the thousands separator. The output is “Number in German: 54.867.593,” showcasing how the locale setting can affect the formatting conventions, in this case, adapting it to German number formatting conventions.

Conclusion

In conclusion, the format() method in Java provides a powerful means to enhance the presentation of data through formatting. Its flexibility in accommodating different data types, locales, and formatting options makes it a valuable tool for developers aiming to create well-structured and locale-specific output.

Whether it’s padding numbers, representing numbers in different bases, or adapting to different language conventions, the format() method empowers developers to produce output that is not only accurate but also visually appealing.

Leave a Reply

Your email address will not be published. Required fields are marked *