How To Format a String In Java With Examples

May 05, 2022
XBlog FormataString



Introduction

Java is one of the most versatile programming languages available in the industry. It not only offers numerous features but also offers a variety of ways to perform such features. Similarly, Java offers multiple Java string format options for its developers. Some of them are simple and straightforward, whereas some are a bit advanced following the object-oriented programming model.

We will be discussing several approaches to achieve a Java string format and how each of these methods is different and would be convenient to use than the others. It will be a suitable guide for you to understand how to perform string formatting in Java whether you are a beginner Java developer or new to the feature of Java string format. 

explore new Java roles

System.out.printf() Method

printf(), which stands for print formatted, is a classic method and is still widely used to date for java string format. You must be familiar with it if you have ever worked on C programming language. It is the primary method used for output in C. The working of the printf() method can be easily understood by its arguments.

The following code snippet shows the most common way for using the printf() method:

System.out.printf(String format, String arguments);  

The parameters or arguments expected by the method includes a string called format and a vararg argument. The format tells the way of how you want your string to be formatted.

For instance, in a certain situation, you might want to display a real number with precisely seven decimal places or maybe in hexadecimal representation. You can also have a predefined message to be displayed for users, but to make it more personalized, you can format it to include the name of the user, entered earlier by the user.

The arguments vararg expects the number of values for the template String. For example, if the template has placeholders for three numbers, the printf() method will also expect three numbers as arguments.

See this line of code:

System.out.printf("%d %d %d ", 42, 23, 75);

Here three %d symbols are entered in the template String. This symbol represents placeholders for a particular data type. The %d is a placeholder for a decimal number value. As there are three of them, the user will have to pass three arguments that are numeric values, such as 42, 23 and 75.

This line of code will just output 3 numbers as shown:

42 23 75

Format Specifiers

printf() method is not limited to showing decimal. In Java string format, you can also use printf() method to print values like Strings, real numbers, dates, and all other types of values. To print each type of value, you need to provide a format specifier for each of the values. 

Let’s take a look at the below example:

System.out.printf("my name is %s", "Ronald");

this code will output “my name is Ronald“ on the screen. The %s symbol represents a format specifier for Strings, just like how %d represents a format specifier for decimal number values. Here it is mentioned that “Ronald” is a string, thus is formatted as a string and printed on the screen. 

There is a list of format specifiers available to be used.

Some of the most common ones includes:

  1. %d – Decimal number (base 10)
  2. %s – String
  3. %x – Hexadecimal number (base 16)
  4. %i – Integer (base 10)
  5. %e – Exponential floating-point number
  6. %c – Character
  7. %f – Floating-point number
  8. %o – Octal number (base 8)
  9. %u – Unsigned decimal (integer) number
  10. %t – Date/time
  11. %n – Newline (for printing new line, printf does not write a newline by default)

Let’s say if you want to print a hexadecimal number and a decimal number, you will be using %x and %d specifiers respectively.

See the code below:

1.	System.out.printf("Hexadecimal to Decimal converter%n");
2.	System.out.printf("Hexademical Value = %x %n Decimal Value = %d ", 223, 223);

Now the result would be:

Hexadecimal to Decimal converter                                 
Hexademical Value = df                                                
Decimal Value = 223 

In this example, 3 different format specifiers are used, along with hexadecimal and decimal, %n is also used twice to shift to a new line after “converter” and after hexadecimal value. 

Escape Characters

Other than format specifiers, there is another type of formatting symbol offered by the printf() method called “Escape Characters.” For instance, if you want to print this symbol ” .

You would probably try this:

System.out.printf(""");

Your attempt seems logical but this is not an acceptable attempt for a Java string format. In the result for this, the compiler will throw an exception as quotation mark has a special, reserved meaning. Quotation marks denote the start and end of a String. What happened here is that instead of printing the middle quotation symbol, it was considered as the closing quotation, leaving the last quotation without closing it. This makes printing the reserved characters impossible.

Java string format offers a solution for this by escaping. To print such reserved characters such as ” or /, we need to first enter the escape symbol to escape its default effects. It can be done in Java string format by using the backslash () prefix with such symbols.

To print a quotation mark in Java without getting an exception, you need to do the following:

System.out.printf(""");

Due to using a backslash before “ ” ” the compiler will know that it needs to be printed and now it will insert the “ ” “ character in that particular place where it will be treated as just a value instead of a reserved symbol.

Following are some commonly used symbols with the escape character:

  1. b – Insert backspace
  2. n – Insert newline
  3. f – Next line’s first character starts to the right of the current line’s last character
  4. r – Insert a carriage return
  5. t – Insert tab
  6. \ – Insert backslash
  7. %% – Insert percentage sign

The last two combination %% and // is a bit interesting one. You might be wondering ‘’why we are not using % to print % ?’’

The “%” character is already a special character specifically used with the printf() method followed by d, i, f and others as a format specifier.

Using “” with the “%” makes “” considered as a format specifier thus compiler will generate an error as there is no such format specifier. To cater to this, “” escapes “” and “%” escapes “%”.

Float and Double Precision

printf() also allows to define custom precision for floating point numbers, like this:

1.	double num1 = 12.12345;
2.	double num2 = 5.123123;
3.	System.out.printf("num1 = %.4f num2 = %.2f", num1, num2);

A decimal (.) along with a number after the % symbol denotes how many digits should be printed after the decimal value for the precision.

This code mentioned above will output the following result:

num1 = 12.1234
num2 = 5.12

Format Padding

Java String format also gives you the option to add padding before or after a passed String with printf() method.

System.out.printf("%10sn", "apple");

“10sn” means there should be 10 characters in the string with the next line in the end. As “apple” only have 5 characters, it will add 5 spaces for padding to the left to complete the String according to the format.

The output will be:

     Apple

By default, the padding is added to the left to complete the format but you can also add the padding to the right instead of by just adding a “–“ sign like this:

System.out.printf("%-10sn", "apple");

It will output it as,

Apple  

Locale

You can also pass a Locale as the first argument in printf () method, to format your string like this:

1.	System.out.printf(Locale.US, "%,dn", 3000);
2.	System.out.printf(Locale.UK, "%,dn", 2000);

This would output two different integers formatted as per the Local passed as argument.

This will be the output:

3,000
2.000

String.format() Method

Another common way of formatting Strings in Java string format is using the String.format() method. The highlighting advantage String.format() provides over the printf() method is its return type. String.format() method returns a String instead of just printing the contents on the screen and has no return type just like the printf() method. String.format() is an ideal option to be used to apply a java string format if you want to reuse the format.

Here is an example of using string.format().

String formattedStr = String.format("current date: %tT", Calendar.getInstance().getTime); 

The following string will be the result if we print the “formattedStr”

Current date and time: Sat Mar 24 14:54:57 PDT 2021

It allows the developer more control over the output string that is formattedStr in this case. Due to the string return data type, it can be printed on the screen, saved into a file or stored in a database.

The String.format() method is based on the same underlying principle as the printf() method. Both of them implicitly use the Formatter class to format the Strings. This means that all the rules set for printf() can also be applied with the String.format() method, so whether you use printf()or String.format(), it will be the same. The only difference here as mentioned before is the return types. String.format() returns a formatted String unlike printf(), which only prints to the standard output stream. This makes String.format() more versatile as it gives developers way more options to perform with the result and it can be used in numerous ways.

System.out.format() method

System.out.format() is another method that can be used to apply the Java string format. The formatter class (discussed after this) has many different methods to output the formatted text to a stream, two of which are format() and the printf() that we have just discussed.

According to the Java documentation for Java string format, they both behave in the same way. This indicates that there is simply no difference between the format() method and printf() method, and you can use either to get the same results. All the features we just discussed including locale, padding, format specifier and the rest, work the same way with format(). Both printf() and System.out.format() print directly to the console/terminal, unlike the format.string() method.

The Formatter Class

All the Java string format methods that we have discussed so far inherently call for the Formatter class. The usage of Formatter class is very similar to all other formatting methods discussed. The only difference is in the way to use it. As it is a class, it requires to first instantiate a Formatter object to use the formatter class.

1.	Formatter f1 = new Formatter();
2.	F1.format("There are %d months in a year.", 12);
3.	System.out.println(f1);

The output will be as expected:

There are 12 months in a year

The question that should come to your mind is that why shouldn’t we just stick to the previous formatting methods as they get the work done in less lines of code and are relatively straight forward and concise? No, it is not that simple. There is one more important feature that makes the Formatter class very versatile.

Take this example:

1.	StringBuilder sb1 = new StringBuilder();
2.	Formatter f1 = new Formatter(sb);
3.	f1.format("%d, %c, %x...n", 1, ‘a’, 38);

Formatter class allows you to work with any other class like StringBuilder that implements the Appendable interface. This includes other classes like FileWriter, PrintWriter, PrintStream, BufferedWriter, StringBuffer and others. Similar to the format() method, Formatter class also allows the use of all format specifiers, escape characters, locale and all other features mentioned with the printf() method.

MessageFormat Class

This is one unique Java string format technique that does not make use of Formatter class, unlike every other method we have discussed so far. MessageFormat aims to produce and output concatenated messages in a language-neutral way. This means that formatting will remain the same, whether you choose to use Java, Python, or any other programming language that supports MessageFormat. MessageFormat extends the abstract Format class which is meant to format locale-sensitive objects into Strings.

See this example below:

1.	int days = 365;
2.	String str1 = "Number of days in a year = ";
3.	String result1 = MessageFormat.format("{1} {2, number, integer}.", str1, days );

Following will be the output:

Number of days in a year = 365.

Instead of using the percentage specifiers that we have been using so far, curly brackets are used here for every argument. The first argument is {1}. The number 1 represents the index of the argument that will be used in this place which is the string, str1. The same will be used for the next argument which is days.

For every value, a more specific selection can be made, like using {2, number, integer} with the second argument. It means that the value must be treated as a number and also as an integer.

See Also: Compression and Decompression of String Data in Java

Conclusion

We have covered almost all Java string format methods that are prominent for Java string format. All these methods are used to format Strings in core Java. Every technique that we have discussed offers its specific use in a certain situation. Printf() is the same as the C method of the same name, so any developer migrating from C would find it relatively easier to use. Another technique like Formatter class is a modern approach that uses the features of object-oriented programming and lastly, MessageFormat is the most unique offering a different method to apply Java string format.

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US