Welcome! In today's lesson, we're delving into String Formatting in Java, an essential feature for presenting data in a neat manner. We'll be exploring the intricate details of format strings, as well as methods such as printf and String.format. Ready? Let's get started!
Our journey begins with understanding the concept of String formatting. This concept reshapes the way we view a string. In Java, it's somewhat akin to enhancing the appearance of existing data. Specifically, format strings are tools we use to 'dress up' our data. These strings employ a delimiter %, along with flags, width, and precision specifications to format the data. A simple example can illustrate this concept quite well:
In this instance, we used %s - a placeholder for a string - that gets replaced by the string Tom.
The other available options include:
%d- integer number%f- float number
Let's explore how width and precision can further refine the display of our string. Width allows us to define a minimum number of characters, while precision sets the limit on the number of decimal digits or characters in a string:
In this case, additional spaces for number are padded to print 5 characters (even though the number has just 3 digits), and percentage is truncated to two decimal places. When we use formattedRight and %-5d, extra whitespaces are added to the right instead.
