String formatting in Java: String.format() method.

Guides for Java Developers
While System.out.println() is good for debugging and displaying simple messages, not good for string formatting. Formatted strings not only display the contents of the string, but also display the contents in a particular string. For example, 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 display a specific number of decimal places such as 199.53 along with rounding. Developers will be happy to know that Java provides several formatting methods with sufficient support for various data types such as Double, Whole numberand Date.

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

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

Syntax of the String.format() method in Java

I you String.format() is a static method that returns a formatted Series using the default language, format Series, 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)
  • place: localization applied during formatting. However, if it is null and void localization is not applied.
  • format: the Series format.
  • arg: parameter referenced by format specifiers in format Series. If there are more arguments than the format specifications, the additional arguments are ignored. The number of arguments can vary and can be omitted entirely.

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 particularly useful for formatting numbers and dates according to the rules of the default locale. For example, here the locale value is “France” which replaces the decimal point with a comma, according to the French 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 String.format() method throws a few exceptions:

  • NullPointerException: This exception is thrown if Series the argument passed null and void.
  • IllegalFormatException: If the specified format is illegal or has insufficient arguments.

Programmers almost never catch these exceptions, because they usually indicate improper use of a method rather than some kind of expected runtime exception.

Read: Java tools to increase productivity

String width, alignment, and padding formatting in Java

The String.format() method also allows developers to set width, alignmentand lining from formatted Series. 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("


Specifying types using String.Format()

As we saw in the localization argument example above, String.format() it can also be used to convert and format other data types to a string. To do this, Java provides an array Format specifiers. They begin with a percent sign (%) and ends with typechartype character“, which indicates the type of data (int, floatetc.) that will be converted, as well as the way in which the data will be presented (decimal, hexadecimaletc.) Complete syntax a Format specifier in Java is:

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

We can see how diverse it is in the program below Format specifiers affect the display 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 Format specifiers for String.format() method:

  • %% “He can”%” sign
  • %x/%X – Hexadecimal integer
  • %t/%T – Time and date
  • %s/%S – Wire
  • %n – Inserts a newline character
  • %on – octal integer
  • %f – Decimal floating point
  • %ii – Scientific record
  • %Mr – Causes the Formatter to use %f or %e, whichever is shorter
  • %h/%H – Hash code of the argument
  • %d – Decimal integer
  • %c – Character
  • %b/%B – Boolean
  • %a/%A – Floating point hexadecimal number

Note that some specifiers can be both lower case or upper case. The case of the specifier is dictated by the case of the formatted letters. In addition, the conversion performed is the same, regardless of upper and lower case letters.

Read: How to concatenate strings in Java

Argument index and String.format()

Remember that from the earlier instruction String.format() can accept more Subjects format. The Index of arguments is an integer indicating the position of the argument in that list Subjects. Not to be confused with Numbered groups from Series to replace() function ($1, 2 dollarsetc.), Argument indices number place AGO dollar sign. Therefore, the first argument is invoked $1second by $2, and so on. Here is a program that formats two pieces of data: a float i.a Series:

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 string formatting in Java

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

Read more Java programming guides and software development guides.

Source link

Leave a Reply

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