String Format Java | Formatting a String | Date Time Format Specifiers
While dealing with string, int, float, long etc. you might require your results to be in a certain format. That’s where String Format Java comes into the picture. Using formatting you could adjust the primitive data types to give results in your desired style.
How do you achieve that? Easy there, tiger. I am coming to it.
- 1 How to Format a String in Java
- 2 Integer and String Formatting
- 3 String Format Java: General Format Specifiers
- 4 Ways to Use String Format Java
- 5 Using String.format()
- 6 Using System.out.format() and printf()
- 7 Using Formatter Class
- 8 Date and Time Format Specifiers
- 9 Grabbing Current Date and Time
- 10 Grabbing a Customized Date and Time
How to Format a String in Java
Up until now, we have seen string in Java up close, now it is time to understand how to format it.
You do so with the help of format specifiers. These are all bunch of codes that are hard coded for your JVM to understand. You need to remember these, if not all at least the important ones that you might need for your code.
The date/time conversion format specifiers might pop up at some point in your life some time. You can note that down or at any day come back here to check it out.
The most basic syntax that string format Java follows is:
“% [argument index] [flag] [width] [.precision] type”
While we are at it, let’s label the above so that we know what’s what. Here’s the legend:
- % is nothing but a special character that tells JVM that a formatting instruction is going to follow.
- [argument index] lets your JVM know about the index of the argument that needs formatting. It is optional.
- [flag] is nothing but a special instruction. E.g. + or – sign to decide padding
- [width] means minimum number of output characters you need
- [.precision] implies the precision of floating point numbers, meaning the no. of decimal digits you want.
- type is a mandatory field that lets JVM know what type you need to format your string in. e.g. s means string, d means integer etc.
Integer and String Formatting
That being said we can take a look at some String Format Java examples, to understand what is in store for us:
What if we had an integer to address. Here’s a small list to answer what does what:
- %d – Prints integer as is
- %8d – If no. of digits is less than 8, prints output padded to the left
- %-8d – If no. of digits is less than 8, prints output padded to the right
- %08d – If no. of digits is less than 8, prints output padded to the left with 0s.
- %.2d – Prints maximum 2 digits of the integer
‘What if we had a string to address? Here’s a list to answer that:
- %s – Prints string as is
- %10s – If no. of digits is less than 10, prints output padded to the left
- %-10s – If no. of digits is less than 10, prints output padded to the right
- %.5s – Prints maximum 5 characters of the string
String Format Java: General Format Specifiers
In Java, you could use format specifiers to let the JVM know that you want your result in a desired data type format. Some examples of frequently used format specifiers are:
- %a = returns Hex output of floating point no
- %b = returns ‘true’ if non-NULL and ‘false’ if NULL
- %c = returns a unicode character
- %d = returns decimal Integer
- %e = returns decimal number in scientific notation
- %f = returns decimal number
- %g = returns decimal number with scientific notation depending upon precision and value
- %h = returns hex string of value from hashCode() method
- %n = returns a line-separator
- %o = returns octal number
- %s = returns a string value
- %t = a prefix for Date/Time conversion (You still need more formatting, refer bottom section)
- %x = returns Hex string
Ways to Use String Format Java
Now comes the part where you learn how to use a format specifier. There are three ways to achieve that in Java:
- Using String.format()
- Using printf() or format() method of System.out and System.err
- Using Formatter class and linking it to StringBuilder
Let’s see each one of them one by one:
It is one of the most sought after ways of string format Java. The String class has a format() method in it which helps in formatting a string. Here’s one example to help you understand:
String s = String.format("%s were %d %s", "There", 3, " people"); System.out.println(s);
The output to the above would be:
There were 3 people
Notice how we need to simply provide as many parameters as many format specifiers are there. So as to simply fill in the blanks.
If you wish to represent a positive no., you could use simply this:
20 is simply being used here to specify right justification so you understand there is no need to use ‘+’ for right justification as is required for ‘-‘ for left justification. You will get the following result:
If you wish to put a negative number simply manually put ‘-‘ sign before the number like this:
To put something in a parenthesis:
Will give you the result:
Try putting them in a mod sign ‘|’ yourself.
Okay if you insist:
The same logic can be applied to string also. If you wish to specify no. of characters to show:
System.out.print(String.format("%.4s", "Hola Amigo!"));
Using System.out.format() and printf()
People often make use of System.out’s printf() and format() methods which work absolutely great when they are low on time. These String format Java methods are so much less work. You can make use of System.out.format() method as well to format a string:
System.out.format("%s is %.2f", "The Time", 12.55);
Notice the dot symbol in the above will simply help us in specifying how many digits we need after the decimal place.
The above will print:
The Time is 12.55
Which is exactly the way wished time to be printed.
Alternatively, System.out.printf() can also be used:
System.out.printf("%s are %d eggs in the basket", "There", 3);
The above code is going to give us a simple answer:
There are 3 eggs in the basket
Using Formatter Class
Here’s the third method to achieve string formatting. You can simply use Formatter class that takes a StringBuilder instance as a parameter.
Here you need to import java.util.Formatter before moving on.
Then create the instances like this example suggests:
StringBuilder s = new StringBuilder(); Formatter f = new Formatter(s); System.out.println(f.format("%s of %s %10d", "Age", "Hawkeye", 35));
Here notice how we have used a number in %10d. It means that I need 10 blank spaces before the age. So the result would become:
Age of Hawkeye 35
What if you need the space on the right side? For that, you are supposed to use the negative value. Let’s see that as well:
System.out.println(a.format("%s of %s %-10d and biceps %10d", "Age", "Hawkeye", 35, 55));
If you run the above you will get the following result:
Age of Hawkeye 35 and biceps 55
Notice we have made use of -10 which is a negative value so as to make it left justified, and for 55 we have used a positive value which makes it right justified.
Date and Time Format Specifiers
As implied from above date and time format specifiers are quite detailed. Here’s a list to help you understand what does what:
- %tA = Name of the day of the week e.g. Sunday
- %tB = Name of the month e.g. January
- %tC = Part of the year formatted in two digits. e.g. 00 to 99 (for years)
- %tD = Date formatted as “%tm/%td/%ty”
- %tH = Hour of the day as per 24 hour clock
- %tR = Time formatted as 24 hour clock
Small letters like %ta, %tb, etc. too provide different formatting. You can experiment that to find out more yourself.
Grabbing Current Date and Time
There might be situations in your coding sojourn wherein you would be asked to grab date and time and put it in the desired format. For that, you could take the aid of a built-in LocalDateTime static Class.
For that you need to, of course, import the following class:
Once you import you can use the now() method of the class in this manner:
LocalDateTime ldt = LocalDateTime.now();
Now time to format it.
We will make use of simple printf to get what we want:
LocalDateTime ldt = LocalDateTime.now(); System.out.printf("%tA %<tB %<tC %n", ldt); System.out.printf("%tD", ldt);
The first format specifier %tA would grab the name of the day. The ‘<‘ sign means that we are reusing the same value from our argument. The rest of the parts are easy to understand.
We have used a simple “%n” to change to the next line.
The result we will get here is, which will differ with yours of course based on the date you have today:
Tuesday June 20 06/20/17
Grabbing a Customized Date and Time
What if there is a log date that we need to put manually?
Don’t worry LocalDateTime has another method called of() that you can use and punch in dates manually.
Here’s an example for that:
LocalDateTime ldt = LocalDateTime.of(2017, Month.APRIL, 23, 12,23,4); System.out.printf("%tA %<tB %<tC %n", ldt); System.out.printf("%tD %n", ldt);
The arguments is simply what I have followed what the method allows us to put. The Month.APRIL part is a Month Class that you need to once again import using:
If you run the above you will get:
Sunday April 20 04/23/17
I think with the aforementioned ranting you now have some idea on how to format local date and time in Java. Bring it to good use soldier.