Formatted Strings – Selected API Classes

Formatted Strings

We have used the System.out.printf() method to format values and print them to the terminal window (§1.9, p. 24). To just create the string with the formatted values, but not print the formatted result, we can use the following static method from the String class. It accepts the same arguments as the printf() method, and uses the same format specifications (Table 1.2, p. 26).

Click here to view code image

static String format(String format, Object… args)

Returns a string with the result of formatting the values in the variable arity parameter args according to the String parameter format. The format string contains format specifications that determine how each subsequent value in the variable arity parameter args will be formatted.

Any error in the format string will result in a runtime exception.

Click here to view code image

String formatted(Object… args)

Formats the supplied arguments using this string as the format string. It is equivalent to String.format(this, args).

The following call to the format() method creates a formatted string with the three values formatted according to the specified format string:

Click here to view code image

String formattedStr = String.format(“Formatted values|%5d|%8.3f|%5s|”,
                                    2020, Math.PI, “Hi”);
System.out.println(formattedStr);  // Formatted values| 2020|  3.142|   Hi|
formattedStr = formattedStr.toUpperCase();
System.out.println(formattedStr);  // FORMATTED VALUES| 2020|  3.142|   HI|

Alternatively, we can use the formatted() method:

Click here to view code image

String formattedStr1 = “Formatted values|%5d|%8.3f|%5s|”
                          .formatted(2020, Math.PI, “Hi”);
System.out.println(formattedStr1); // Formatted values| 2020|  3.142|   Hi|

For formatting strings in a language-neutral way, the MessageFormat class can be considered (§18.7, p. 1139). Other miscellaneous methods exist in the String class for pattern matching (matches()), splitting strings (split()), and converting a string to an array of bytes (getBytes()). The method hashCode() can be used to compute a hash value based on the characters in the string. Please consult the Java SE Platform API documentation for more details.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *