Apps/Gaming

Formatting Strings in Java: String.format() Method

while System.out.println() is fine for debugging and displaying simple messages, it is not great for formatting strings. Formatted strings not only display the string content but they also show the content in a specified sequence. For instance, when displaying large integers like 100000000you may want to include commas so that it appears as 100,000,000. Similarly with decimal numbers, you might want to show a specific number of decimal places like 199.53 along with rounding. Programmers will be happy to know that Java offers a few formatting methods with ample support for a variety of data types like doubles, integerand dates.

There are three primary ways to format a string in Java. You can use the String.format() method, the printf() method, or the MessageFormat class for formatting strings. Of these, the String.format() method is the most commonly used, so we will be covering it in this Java programming tutorial. We will get to the other two options in a future article.

If you need a refresher or missed our previous tutorial on working with strings in Java, be sure to visit: Java Output Basics.

String.format() Method syntax in Java

Java’s String.format() is a static method that returns a formatted thong using the given locale, format thong, and arguments. It comes in two flavors, as follows:

public static String format(String format, Object… args) public static String format(Locale locale, String format, Object… args)

  • locale: the locale applied during formatting. However, if it is zero the localization is not applied.
  • format: the thong to format.
  • sorry: the parameter referenced by format specifiers in the format thong. If the arguments are more than the format specifiers, the extra arguments are ignored. The number of arguments may vary and may be omitted completely.

Here is an example of how to use String.format() in Java:

class StringFormatExample { public static void main(String[] args) { String name = “Rob Gravelle”; String str = String.format(“My name is %s”, name); System.out.println(str); // My name is Rob Gravelle } }

The locale argument is especially useful for formatting numbers and dates according to the rules of a given locale. For example, here is a locale value of “France” that replaces the decimal point with a comma, as per the France number system:

import java.util.*; class StringFormatLocaleExample { public static void main(String[] args) { System.out.format( Locale.FRANCE, “The value of the float ” + “variable is %f “, 10.3242342 ); // The value of the float variable is 10.324234. } }

String.format() Exceptions in Java

You should be aware that the String.format() method throws a couple of exceptions:

  • NullPointerException: This exception is thrown if the thong argument passed is zero.
  • IllegalFormatException: If the format specified is illegal or there are insufficient arguments.

Developers almost never catch these exceptions, as they tend to indicate improper use of the method rather than some kind of expected runtime exception.

Reading: Java Tools to Increase Productivity

Formatting String Width, Alignment, and Padding in Java

the String.format() method also allows programmers to set the width, alignment, and padding of the formatted thong. The following class contains examples of each, as well as various combinations:

public class StringFormatWidthAndPaddingExample { public static void main(String[] args) { String greeting = “Hi Rob”; // Text width String.format(“|%20s|”, greeting); // | Hi Rob| System.out.println(greeting); // Left justify text String.format(“|%-20s|”, greeting); // |Hi Rob | System.out.println(greeting); // Maximum number of characters String.format(“|%.3s|”, greeting); // |Hi | System.out.println(greeting); // Max. characters with width String.format(“|%20.3s|”, greeting); // | Hi | System.out.println(greeting); } }

Specifying Types with String.Format()

As we saw in the locale argument example above, String.format() can also be used to convert and format other data types into a string. To do that, Java provides a variety of format specifiers. These begin with a percent character (%) and terminate with a typechar “type character“, which indicates the type of data (internal, floatetc.) that will be converted, as well as the way in which the data will be represented (decimals, hexadecimaletc.) The full syntax of a Format Specifier in Java is:

% [flags] [width] [.precision] [argsize] typechar

We can see in the program below how various Format Specifiers affect the displaying of data:

import java.util.Date; public class StringFormatTypesExample { public static void main(String[] args) { String str1 = String.format(“%d”, 2112); // Integer value String str2 = String.format(“%f”, 98.7); // Float value String str3 = String.format(“%x”, 101); // Hexadecimal value String str4 = String.format(“%o”, 023); // Octal value String str5 = String.format(“%tc”, new Date()); // Date object String str6 = String.format(“%c”, ‘Z’); // Char value System.out.println(str1); // 2112 System.out.println(str2); // 98.700000 System.out.println(str3); // 65 System.out.println(str4); // 23 System.out.println(str5); // Thu Jan 05 20:52:06 GMT 2023 System.out.println(str6); // Z } }

Here is the full list of Format Specifiers for the String.format() method:

  • %% – insert a “%” sign
  • %x/%X – Integer hexadecimal
  • %d/%T – Time and date
  • %s/%s – thong
  • %n – Inserts a newline character
  • %O – Octal integer
  • %f – Decimal floating point
  • %e/%E – Scientific notation
  • %G – Causes Formatter to use either %f or %e, whichever is shorter
  • %h/%H – Hash code of the argument
  • %d – Decimal integer
  • %c – Characters
  • %b/%B – Boolean
  • %a/%A – Floating point hexadecimal

Note that some specifiers may be either lowercase or uppercase. The case of the specifier dictates the case of the formatted letters. Other than that, the conversion performed is the same, regardless of case.

Reading: How to Concatenate Strings in Java

Argument Index and String.format()

Recall from earlier in the tutorial that String.format() can accept multiple objects to format. The argument index is an integer indicating the position of the argument in that list of objects. Not to be confused with the Numbered Groups of the thong replace() functions ($1, $2, etc.), Argument Indexes place the number BEFORE the dollar sign. Hence, the first argument is referenced by 1$the second by 2$, and so on. Here is a program that formats two pieces of data: a float and a thong:

public class StringFormatArgumentIndexExample { public static void main(String[] args) { String product = “Bread”; double price = 4.99; String str = String.format(“The price of %2$s is CAD $%1$.2f today.”, price, product); // The price of Bread is CAD $4.99 today. System.out.println(str); } }

Final Thoughts on Formatting Strings in Java

Although there are several ways to format a string in Java, the String.format() method is the most commonly used due to its tremendous versatility. From localization, type conversion, width, alignment and padding, it has got you covered!

read more Java programming tutorials and software development guides.

Related posts

Best practices for remote development teams

TechLifely

How to Use the Java Platform Environment

TechLifely

What is Agile Project Management?

TechLifely

Leave a Comment