String Formatting using format in Java

By | March 18, 2022
String Formatting using format in Java

Introduction

We usually use System.out.println or System.err.println to print messages on the console. But to use the printf formatting options, we can use the System.out.format methods or System.err.format methods.

Formatting output with System.out.format

Formatting output using above methods will eliminate the plus signs we otherwise use to merge the values together and make the code more readable and understandable. Let us first see the usual way of printing using println:

String name = "Joe";
float average = 79.45f;
Date currdate = new Date();
System.out.println("Hi, my name is " + name + ", average marks are " + average + " and today's date is " + currdate + ".");

Note that we have to format the sentence multiple times, taking care of the spaces, commas, etc., and appending the strings and other variables multiple times. We also have to add a full stop separately.

Let us now see the magic of the format method:

System.out.format("Hi, my name is %s, average marks are %.2f and today's date is %s.", name, average, currdate);

We printed the entire sentence easily without having to append the variables by inserting the right variable type symbols in the right place and then adding the comma-separated variables in the same order as they have to be inserted.

Note that the ‘.2’ in %.2f is used to limit the float value to two decimal places, else the program will print the full value. If you want to print an integer (decimal), you should use %d. If there is a mismatch in the data types, you will get a java.util.IllegalFormatConversionException

The important point here is to pass the correct order of variables, especially of the same type. Below is an example of how the sentence can become INVALID because of the wrong placement of parameters:

Vamware
System.out.format("Hi, my name is %s, average marks are %.2f and today's date is %s.", currdate, average, name);

The same works for System.err.format as well.

Conclusion

There are many formatting specifiers in the printf format for different variables. For example, to print percent sign, use %% or \%, for a character, use %c, for exponential numbers, use %e, and so on.

Vamware

People are also reading: 

Author: Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

Leave a Reply

Your email address will not be published.