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:
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.
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.
People are also reading:
Leave a Comment on this Post