Register Login

Format Strings in Java

Updated Jan 09, 2023

Almost every programming language has a long tradition of string formatting. There are many distinct ways to format strings in Java.

Java has functions that help users to format strings, such as printf() and format(), while the rest of the methods are more in the spirit of object-oriented programs, such as the Formatter and the MessageFormat class. In this article, Java users will learn how to format strings easily with the techniques and functions; named above.

What is meant by formatting strings in Java?

In Java, formatting string, also called String interpolation, is the insertion method of any custom string or variable in a predefined text. Users can use this to insert more lines or little titles in a graph, display an error message or a simple message, or insert a statement into a function. Some of the techniques for formatting strings are as follows:

Using printf() to format strings in Java :

It is one of the old classic methods of formatting strings in Java. The printf function prints a new Java string on the user's screen using the "format string" that has the instructions to combine multiple strings and generate a final string output.

The interpreter then prints the Java string on the screen. The name of the function came from "print formatted." Users can understand the way printf() works by its arguments.

The most typical method of using printf() is as follows:

Syntax:

System.out.printf(String format, String ... arguments);

Here, the function expects a format and an argument. The format argument specifies how a user wants the format of the Java string and a template for the final string output.

Code Snippet:

public class Main
{
	public static void main(String[] args) {
		System.out.printf("Hello, %s!%n", "Michael Scott");
        System.out.printf("Hello, %s!%n", "Jim");
        System.out.printf("Hello, %s!%n", "Dwight");
	}
}

Output:

Explanation:

The printf() function prints the statements, and we have added the new line character to create a new line in the output.

As we can see, to print the values in the printf() function, we need some special characters having the percent character "%." These are called format specifiers.

There are different types of format specifiers having their functionalities. These are as follows:

  • %c: Users can use this format specifier to print all the characters in the output console.
  • %d: This helps print all the decimal numbers having base ten.  
  • %e: With this format specifier, users can print all the exponential floating-point numbers in the output console.
  • %f: It helps to display all floating-point numbers in the console written in the printf() function.
  • %i: It prints all decimal integers, i.e., having base ten.
  • %n: To enter a new line in the output, users use the %n format specifier that inserts a new line character.
  • %o: It helps to print all the octal numbers (numbers having base eight).
  • %s: To insert a string, users need the %s format specifier. It is known as format character.  
  • %t: Users can use this format specifier to print time and date in the output console.
  • %u: This format specifier is specific for all the unsigned decimal numbers (or integer values).
  • %x:  It prints all the hexadecimal numbers (having base sixteen).
  • %%: To add a "%" (percent symbol), users can use the double percent character (%%).
  • %e%E: It inserts scientific notations.

Code Snippet :

public class Main
{
	public static void main(String[] args) {
		System.out.printf("Hello, %d!%n", 45346);
        System.out.printf("Hello, %s!%n", "Jim");
        System.out.printf("Hello, %e!%n", 45346.57457324);
	}
}

Output:

Explanation:

Here, we used the %s, %d, %e to print the decimal number, string character, and a long exponential floating-point number. Users can use one or more format specifiers according to the requirement of their input string.

Using format() to format strings in Java :

It is another way to format strings in Java. The String.format() method internally operates java.util.Formatter. It is one of the most significant features that becomes an advantage of String.format() over printf().

The String.format() returns a string as a return type. Java users can use the String.format() for formatting the string that users can use or reuse in the future.

Syntax:

public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();  
}

Code Snippet:

public class Main
{
	public static void main(String args[]){  
        String demo = "Hello Java";  
        String a = String.format("The sample is %s", demo);  
        String b = String.format("the value is %f", 324.745);  
        String c = String.format("the value is %32.12f", 324.745345756564); //it returns twelve char fractional part filling with zero  
  
        System.out.println(a);  
        System.out.println(b);  
        System.out.println(c);  
}} 

Output:

Explanation:

Similar to the printf() function, the String.format() method operates the same underlying principles. Both these two Java functions internally use the Formatter class to format the string input in Java.

Using formatter to format strings in Java:

Let us know how the formatter works as it is the most critical method among all other methods because both the above functions inherently call the Formatter. So knowing and understanding it will mean that a user knows all of them within a single method.

Instead of working only with Strings, it allows users to work with StringBuilder, which causes it doable to use and reuse both classes efficiently.

Code Snippet:

import java.util.*;
public class Main {
	public static void main(String[] args) {		
		Formatter a = new Formatter();
		a.format("%2$5s %1$5s %3$5s", "Java", "Hello", "World");
		System.out.println(a);		
		a = new Formatter();
		a.format(Locale.FRANCE,"%.5f", -234536.67567);
		System.out.println(a);
	     String demo = "Formatter";
	     a = new Formatter();
	     a.format(Locale.US,"Hello %s !", demo);
	     System.out.println("" + a + " " + a.locale());	   
	     a = new Formatter();
	     a.format("%.4f", 123.1234567); 
	     System.out.println("Decimal floating-point notation up to four places: " + a); 	     
	     a = new Formatter();
	     a.format("%010d", 3456); 
	     System.out.println("The ten digit value is: " + a); 
	}
}

Output:

Using MessageFormat to format strings in Java :

MessageFormat extends an abstract Format class similar to the NumberFormat and DateFormat. The Format class structures locale-sensitive objects into Strings as outputs.

Java has MessageFormat to create and displays concatenated messages in a language-neutral format. It indicates that the formatting will remain the same, despite of whether the user uses Python, Java, or any other programming language that supports MessageFormat.

Code Snippet:

import java.text.MessageFormat;
import java.util.Date;
import java.util.Random;
public class Main {     
    public static boolean a(int x) {
        if (x == 2) return true;
         
        for(int i=2;i<=(int)Math.sqrt(x)+1;i++) 
            if(x%i == 0) 
                return false;
         
        return true;
    }
 
    public static void main(String[] args) {
     
        int[] nums = new int[10];
        Random rnd = new Random();
         
        for (int i=0;i<nums.length;i++) {
            nums[i] = rnd.nextInt(100);
        }
         
        int b = 0;
         
        for (int num : nums) {
            if (a(num)) b++;
        }
         
        String demo = "We found the prime numbers at {0,time} on {0,date}, there are {1} prime numbers";
        MessageFormat mf = new MessageFormat(demo);
         
        System.out.println(mf.format(new Object[] {new Date(), b}));
 
    }
 
}

Output:

Conclusion:

We hope this article has glossed over all four critical techniques of formatting strings in Java. Each of the above ways we have presented has its justification for existence. All these methods are modern approaches to format Java string that uses some advantages of object-oriented programming.


×