String formatting is a challenging task that many developers face while working with string data. Luckily, Java offers various built-in methods to deal with this task, and the “printf()” is one of them. This method accepts a string, formats it (according to the specified specifier), and prints it on the console. Not only strings; you can also format data of other types using this method, such as numbers, booleans, dates, etc.
Considering the significance of the printf() method, this post will use this method to format a string in Java.
How to Format a String With printf() in Java
You can use one of the following signatures to format a string using printf() method in Java. The choice of which variant to use depends on your program’s requirements/preferences:
//with one argument
System.out.printf(stringToPrint);
//with one argument
System.out.printf(format stringToFormat, var1, var2, ...);
//with one argument
System.out.printf(locale, format stringToFormat, var1, var2, ...);
- First Variant: It works exactly the same as the print() method. If it is used with the “%n” character, then it works the same as the println() method.
- Second Variant: This is the most used variant which formats the given strings/objects/variables according to the specified string format.
- Third Variant: If you use the printf() method with the “locale” parameter then the given string will be formatted according to the specified region.
Note: The “stringToFormat” defines how the string/variable will be formatted.
How printf() Method Works in Java
The “stringToFormat” parameter of the printf() method accepts different format specifiers(conversion characters) and the string is formatted accordingly. These format specifiers are used based on the respective data type, as shown in the following table:
Format Specifier | Description |
---|---|
c | It formats the given character/char in the given case. |
C | It formats the character/char in Uppercase. |
s | It formats the given String/text in a given letter case. |
S | It formats the String/text in Uppercase. |
d | It is used to format a digit/integer. |
f | It helps us format a floating-point value. |
t | It formats the date and time values. |
b | Formats the boolean output in the given letter case. |
B | Formats the boolean output in uppercase. |
e | It is used to format the exponential floating numbers. |
%n | It is used to add a new line. |
Be careful while specifying a format specifier in the printf() method, otherwise, you may encounter an error.
Example 1: Formatting Strings in Java Using printf()
In the below code, we create a couple of strings and a character-type variable:
public class StringFormattingJava {
public static void main(String[] args) {
String empName = "John";
String profession = "Author";
char gender = 'M';
System.out.printf("The employee name is %s%n", empName);
System.out.printf("The employee is an %s by profession %n", profession);
System.out.printf("The employee's Gender is %c ", gender);
}
}
We use the printf() method with the “%s” and “%c” specifiers to print the given strings and characters on the console, respectively. Note that, we also use the “%n” character to move the cursor to a new line before printing the next statement. The final output looks like this:
Example 2: Formatting Strings in Uppercase Using printf()
Replace the “%s” and “%c” with the “%S” and “%C” specifiers to get the given strings and characters in uppercase:
public class StringFormattingJava {
public static void main(String[] args) {
String empName = "John";
String profession = "Author";
char gender = 'm';
System.out.printf("The employee name is %S%n", empName);
System.out.printf("The employee is an %S by profession %n", profession);
System.out.printf("The employee's Gender is %C ", gender);
}
}
The output snippet demonstrates that the given strings/characters are formatted in capital letter case:
Example 3: Formatting Strings With Precision
We can specify the precision in the printf() method to format the given string with specified precision. For instance, the following code uses “4” as precision as a result, the first four characters of the given string will be extracted and retrieved:
public class StringFormattingJava {
public static void main(String[] args) {
String domainName = "JavaBeat.net";
System.out.printf("The Extracted String is %.4s", domainName);
}
}
As expected, the first four characters of the specified string are retrieved in the output:
Example 4: Formatting/Padding Strings With Whitespaces
We can specify the string width in the printf() method. In that case, if the given string’s length is the same as the specified width, then the original string will be printed without any change. However, if the width is more than the specified string’s length, then the string will be left-padded with extra whitespaces, as shown below:
public class StringFormattingJava {
public static void main(String[] args) {
String empName = "JavaBeat.net";
System.out.printf("String With Exact Width is %12s%n", empName);
System.out.printf("String With Extra Width is %15s%n", empName);
}
}
In the first statement, we use string width “12” which is equal to the string’s length. So, the string will be printed as it is. While the second statement will add 3 extra spaces before the given string, as illustrated in the following output:
Example 5: Formatting Non-String Values in Java Using printf()
In this example, we create an integer, a floating-point number, a DateTime value, and a boolean value:
public class StringFormattingJava {
public static void main(String[] args) {
int empAge = 28;
float empSal = 50000f;
Date currentTime = new Date();
boolean isPermanent = false;
System.out.printf("The employee Age is %d%n", empAge);
System.out.printf("The employee's Salary is %f%n", empSal);
System.out.printf("Salary in exponential format %e%n", empSal);
System.out.printf("The Current Time is %tT %n", currentTime);
System.out.printf("Is the employee permanent: %b ", isPermanent);
}
}
We use the “%d”, “%f”, “%e”, and “%b” specifiers in the printf() method to format the given integer, floating point value, exponential value, and a boolean value. Also, we use the “%tT” format to format the current time. Note that, the “T” character is used to get the complete current time. You can use the “%tH”, “%tM”, or “%tS” to format the hour, minute, or second field, respectively:
Potential Exception: IllegalFormatConversionException
The printf() method throws an IllegalFormatConversion exception if the specified variable’s type and specifier are not compatible:
To fix this error, specify a valid specifier, (i.e., “%s” in this case):
The above snippet clarifies that the use of the appropriate format specifier resolved the stated exception.
Alternative Approaches to Format a String in Java
The below table discusses the useful alternative approaches (along with pros and cons) to formatting a string in Java:
Alternatives | Description |
---|---|
String.format() | It formats a string and returns it(without printing it). You can print the formatted string using print() or println(). It’s very helpful in cases when we have to store a formatted string for later use. |
MessageFormat.format() | It allows advanced and complex formatting features, such as date formatting, message formatting, etc. |
print() or println() | If a user wants to print the given strings, numbers, etc., then he can use the print() or println() method instead of printf(). These methods are user-friendly and are easy to implement. |
So, this is how you can format a string with printf() in Java.
Final Thoughts
To format a string with printf() in Java, execute the “System.out.printf()” statement with the “%s” or “%S” format specifier. Also, you can use specifiers like “%d”, “%b”, “%t”, etc., to format a number, boolean, date, or time value. You must use an appropriate format specifier in the printf() method to avoid unexpected exceptions as illustrated in this post. This write-up has discussed several examples of string formatting using the printf() method. Also, we have depicted the potential exceptions and some alternate approaches for string formatting.