Format string in Java

In Java, to format a string to include what values, where these values are taken, you can use the static format() method of the String object along with the format you want. To format and print a string to the console, you can use the System.out.printf() method along with the format you want. How is it in detail? We will find out together in this tutorial!

First, I will take the following string as an example “Welcome to Huong Dan Java”. If you want to print this string to the console, you can use the following line of code:


Very simple, right?

If the value of the string “Huong Dan Java” from the above string is taken from a variable, you can rewrite it as follows:

But if your string is as long as “Welcome to Huong Dan Java. My name is Khanh” with the string “Khanh” also taken from a variable, then adding the string like this will be very confusing:

Right guys?

You can format this string for clarity as follows:

The first parameter of the printf() method is “Welcome to %s. My name is %s”, which is a formatted string of characters.

The “%s” character in this first parameter will be replaced by String data type variables declared after this parameter. We have 2 characters “%s”, so we will need to declare 2 variables of data type String, “site” and “name”.

You can see that our code will be easier to see than the string concatenation above.

The “%s” character also allows us to right padding and left padding the value of the substitution variable. In short, the right padding will display the value of the replacement variable with the correct length that we declare. If the replacement string is larger than the length we want, the result will show that string. If the string is less than the length we want, our string will shift to the left, and the missing part of the length will be replaced with the characters we want. For example, if I want to right padding with the replacement character as space for the value of the “site” variable above, I will write the following code:


20 is the length I want the value of the site variable to be displayed, for right padding, we will add a “-” sign. As you can see, my string “Huong Dan Java” will be displayed with spaces after it. Right padding is the padding on the right.

Left padding is the opposite of right padding. Our string will shift to the right, the remainder will be displayed using the replacement character. With the space character, you can write the following:


For a variable whose value type is number, we will use the character “%d” instead of “%s”.

For example, I have the following string:

%d will be replaced with the value of the “age” variable.


If you want to display the age in 3-digit format, if the value of the variable is not enough 3 digits, add leading zeros, you can write the following code:


How many leading zeros you want to add, just increase or decrease the number 3 in “%03d”.

Add Comment