Monday, January 9, 2023
HomeSoftware DevelopmentFormatting Strings in Java: String.format() Methodology

Formatting Strings in Java: String.format() Methodology


Java Developer Tutorials
Whereas System.out.println() is okay for debugging and displaying easy messages, it isn’t nice for formatting strings. Formatted strings not solely show the string content material however additionally they present the content material in a specified sequence. For example, when displaying massive integers like 100000000, chances are you’ll wish to embody commas in order that it seems as 100,000,000. Equally with decimal numbers, you would possibly wish to present a particular variety of decimal locations like 199.53 together with rounding. Programmers might be joyful to know that Java presents just a few formatting strategies with ample assist for a wide range of information varieties like Double, Integer, and Date.

There are three major methods to format a string in Java. You should use the String.format() technique, the printf() technique, or the MessageFormat class for formatting strings. Of those, the String.format() technique is probably the most generally used, so we might be masking it on this Java programming tutorial. We’ll get to the opposite two choices in a future article.

In case you want a refresher or missed our earlier tutorial on working with strings in Java, remember to go to: Java Output Fundamentals.

String.format() Methodology Syntax in Java

Java’s String.format() is a static technique that returns a formatted String utilizing the given locale, format String, and arguments. It is available 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 utilized throughout formatting. Nonetheless, whether it is null the localization is just not utilized.
  • format: the String to format.
  • args: the parameter referenced by format specifiers within the format String. If the arguments are greater than the format specifiers, the additional arguments are ignored. The variety of arguments can fluctuate and could also be omitted utterly.

Right here is an instance of the right way to use String.format() in Java:

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

The locale argument is very helpful for formatting numbers and dates in accordance with the principles of a given locale. For instance, here’s a locale worth of “France” that replaces the decimal level with a comma, as per the France quantity system:

import java.util.*;

class StringFormatLocaleExample {
  public static void principal(String[] args) {
    System.out.format(
      Locale.FRANCE, 
      "The worth of the float " + "variable is %f  ",
      10.3242342
    ); // The worth of the float variable is 10,324234.
  }
}

String.format() Exceptions in Java

You need to be conscious that the String.format() technique throws a few exceptions:

  • NullPointerException: This exception is thrown if the String argument handed is null.
  • IllegalFormatException: If the format specified is against the law or there are inadequate arguments.

Builders virtually by no means catch these exceptions, as they have a tendency to point improper use of the strategy reasonably than some type of anticipated runtime exception.

Learn: Java Instruments to Enhance Productiveness

Formatting String Width, Alignment, and Padding in Java

The String.format() technique additionally permits programmers to set the width, alignment, and padding of the formatted String. The next class accommodates examples of every, in addition to varied mixtures:

public class StringFormatWidthAndPaddingExample {
  public static void principal(String[] args) ", greeting);
    // 
}

Specifying Varieties with String.Format()

As we noticed within the locale argument instance above, String.format() will also be used to transform and format different information varieties right into a string. To try this, Java supplies a wide range of Format Specifiers. These start with a % character (%) and terminate with a typecharsort character“, which signifies the kind of information (int, float, and many others.) that might be transformed, in addition to the best way by which the info might be represented (decimal, hexadecimal, and many others.) The complete syntax of a Format Specifier in Java is:

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

We are able to see in this system under how varied Format Specifiers have an effect on the airing of knowledge:

import java.util.Date;

public class StringFormatTypesExample {
  public static void principal(String[] args) {
    String str1 = String.format("%d", 2112); // Integer worth
    String str2 = String.format("%f", 98.7); // Float worth
    String str3 = String.format("%x", 101);  // Hexadecimal worth
    String str4 = String.format("%o", 023);  // Octal worth
    String str5 = String.format("%tc", new Date()); // Date object
    String str6 = String.format("%c", 'Z');  // Char worth
    
    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
  }
}

Right here is the complete record of Format Specifiers for the String.format() technique:

  • %% – Inserts a “%” signal
  • %x/%X – Integer hexadecimal
  • %t/%T – Time and Date
  • %s/%S – String
  • %n – Inserts a newline character
  • %o – Octal integer
  • %f – Decimal floating-point
  • %e/%E – Scientific notation
  • %g – Causes Formatter to make use of both %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

Be aware that some specifiers could also be both lowercase or uppercase. The case of the specifier dictates the case of the formatted letters. Apart from that, the conversion carried out is identical, no matter case.

Learn: Methods to Concatenate Strings in Java

Argument Index and String.format()

Recall from earlier within the tutorial that String.format() can settle for a number of Objects to format. The Argument Index is an integer indicating the place of the argument in that record of Objects. To not be confused with the Numbered Teams of the String change() operate ($1, $2, and many others.), Argument Indexes place the quantity BEFORE the greenback signal. Therefore, the primary argument is referenced by 1$, the second by 2$, and so forth. Here’s a program that codecs two items of knowledge: a float and a String:

public class StringFormatArgumentIndexExample {
  public static void principal(String[] args) {
    String product = "Bread";
    double worth = 4.99;
    
    String str = String.format("The worth of %2$s is CAD $%1$.2f at this time.", worth, product);
    
    // The worth of Bread is CAD $4.99 at this time.
    System.out.println(str);
  }
}

Closing Ideas on Formatting Strings in Java

Though there are a number of methods to format a string in Java, the String.format() technique is probably the most generally used as a consequence of its large versatility. From localization, sort conversion, width, alignment and padding, it’s got you lined!

Learn extra Java programming tutorials and software program growth guides.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments