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:

Java
String name = "Tom";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);  // Prints: Hello, Tom!

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:

int number = 123;
double percentage = 90.32167;

// `%5d` specifies a minimum width of 5 characters for an integer, adding extra whitespaces to the beginning
// `%-5d` is the same as `%5d`, but whitespaces are now added to the end of the number
// `%.2f` limits the output to 2 decimal digits for a float number
String formatted = String.format("Number: %5d, Percentage: %.2f", number, percentage);
System.out.println(formatted);  // Prints: Number:   123, Percentage: 90.32
String formattedRight = String.format("Number: %-5d, Percentage: %.2f", number, percentage);
System.out.println(formattedRight);  // Prints: Number: 123  , Percentage: 90.32

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.

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