Overview of Java String Formatting

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!

Fundamentals of String Formatting in Java

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
Control Over Formatting With Width and Precision

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.

Padding and Aligning Strings

To enhance the data display, we can adjust alignment and padding, filling extra spaces with specific characters. In this example, we fill the additional spaces with 0:

This is particularly useful when numbers need to align to the right and have the same number of digits.

Use of 'printf' and 'String.format' for Formatting

Java provides printf, an alternative to String.format, for string formatting. printf is similar to String.format, but it prints directly to the console. Here's how it works:

Real-world Examples and Applications of String Formatting

To wrap up, let's consider a practical application of string formatting. Suppose we need to print a report on students' grades in a table-like structure:

Such formatting substantially improves data readability.

This example is pretty advanced, so don't hesitate to ask me to clarify it if you need any help!

Lesson Summary

Great job! We've covered String formatting in Java. Now, it's time to put your newly acquired skills to the test. Remember, practice is key to solidifying concepts and automating your coding skills. Let's move on to the exercises. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal