Strings are an extremely important part of the Java language. Most of the data that we receive is stored in the form of Strings because they are easy to manipulate, read, and store. Java API also provides methods for parsing and converting Java string into different other data types. There are also many methods and format specifiers to construct a string in the way we want.
How to Format Java String?
There are many ways in which Java string can be formatted. The most common way is to use String.format(). Similarly, for console output, where we usually use System.out, we can use printf() or format(). Sometimes, it is also easy to use StringBuilder and Formatter classes. Let us explore each method in detail.
Method 1: String.format()
This is the most common method to format Java Strings. We can say that this is similar to a ‘printf’ statement. Some examples:
String formatted = String.format("%s, %d, %f", "Paula", 35, 89.25); System.out.println(formatted);
We have format specifiers as a string, integer, and floating-point for the arguments.
String formatted2 = String.format("She is %s, %d years old and passed with %f in Physics Honors", "Paula", 35, 89.25); System.out.println(formatted2);
As you can see, the output is formatted exactly how you want it to be. A typical example of date-time formatting is given below:
Date dt = new Date(); String formatted3 = String.format("Hey, %s! Were you born on a %tA in the month of %tB?", "Paula", dt, dt); System.out.println(formatted3);
Method 2: printf() or format()
These methods are present in the System.out and System.err print streams.
System.out.printf("Today is %tA and the date is %tD", dt, dt);
Method 3, StringBuilder and Formatter
In this method, we will use the string builder to construct a string and then use a formatter to format the same. The advantage of using a StringBuilder is that we can keep appending to the same string at any point of time. Let us look at an example:
Date dt = new Date(); StringBuilder sb = new StringBuilder(); Formatter fmt = new Formatter(sb); fmt.format("Today is %tD.\n", dt); sb.append("We missed the match yesterday. "); fmt.format("It is a %tA today, so let us go for a movie at least!\n", dt); fmt.format("Let's call %s, %s and %s too!", "Samantha", "Sean", "David"); sb.append("\nIt will be good fun."); System.out.print(sb.toString());
We have used quite a few format specifiers in this article for date, string, and int. There are different format specifiers for other types, like %f for float, %b for Boolean, etc. If the correct format specifier is not given, the program will throw an IllegalFormatConversionException. For example, if you give a float value but use the %d, you will get this exception. So, be wise in choosing the specifiers in your program.
People are also reading: