Output Formatting in Java

Harsh Parashar
2 min readJun 4, 2019

--

In Java, printf function can be used with some special type of formatting characters to print the output in a specific way. It is very useful to print the data into a table form to make it look more understandable.

Here, today in this example, I will show you the use of “%-15s%03d%n”.

In the example above, the output will be formatted according to the symbols:

output

Here, the string ‘s1’ is formatted using “%-15s”. The ‘%’ sign mean that the following strip is the formatting argument. The ‘-’ means that the output will be aligned to the left. ‘15’ is the number of blocks that the first string is going to take filled up with the string characters first and then rest with the spaces and finally ‘s’ means that you are formatting a string.

Then, the int ‘x’ is formatted using “%03d”. Here, ‘0’ denotes the necessary fill character. ‘3’ again is the number of blocks or width that the integer value can use. If the integer value is less than 3 digits then the rest of the block(s) will be filled with zero (0) at the beginning and finally ‘d’ denotes that you are formatting an integer value.

“%n” specifies a new line.

--

--

Harsh Parashar

Tech enthusiast, Big AI fan, looking to dive deep in the technology field. I share my knowledge and research here.