Java String format()The Java String class format() method returns the formatted string by given locale, format and arguments. If we do not specify the locale in String.format() method, it uses the default locale by calling Locale.getDefault() method. The format() method of the Java Sting class is the same as sprintf() function in c language, and printf() method of Java System Java language. The format() method of Java language is like sprintf() function in C language and printf() method of Java language. Internal ImplementationMethod SignatureJava String class format() method provides following two variants: and, Parameters:locale: It specifies the locale to use on the format string. A local area represents a specific geographical, political, or cultural area. It defines conventions such as datetime format, number format, and currency symbol. By default, if this parameter is not provided, the String.format() method uses the default location of the JVM. format: It represents the quality of the string. It also contains static text and format specifiers that are placeholders for arguments. Format specifiers use a percentage sign (%) followed by variable characters (such as 's', 'd', 'f') that specify the type of data to be entered. args: It represents the contents of the format string. The format string can have zero or more arguments matching the format designators. The type and number of arguments must match the format specifiers in the format string. Returns:The String.format() method returns a formatted string based on the provided format string and arguments. Exception Throws by The format() MethodNullPointerException: If the format parameter is zero, this exception is thrown. If the format string is null, the method cannot be formatted and raises a NullPointerException. IllegalFormatException: An exception is thrown if the format string is illegal or does not match the supplied arguments. For example, if the format string contains insufficient information for format specifiers, or if the format string contains invalid conversion characters, an IllegalFormatException is thrown. Example:In this example: The Locale.US parameter specifies that the formatting should follow the convention of the United States locale. The format number is "Hello, %s! You have %d new messages. Two formats are specified: %s for string and %d for integer." The arguments "John" and 5 correspond to the %s and %d format specification, respectively. The method returns a formatted string, which is then printed to the console. Understanding these parameters and exceptions is important to properly use the String.format() method in Java, ensuring proper formatting and handling possible errors. Java String Format SpecifiersHere, we are providing a table of format specifiers supported by the Java String.
Java String.format() Method ExampleExample-1 File Name: FormatExample.java Output: name is sonoo value is 32.334340 value is 32.334340000000 Explanation: sf1 formats a string with the placeholder %s, resulting in "name is sonoo". sf2 formats a float with %f, resulting in "value is 32.334340". sf3 formats a float with a minimum width of 32 characters and 12 decimal places using %32.12f, resulting in "value is 32.334340000000 These examples illustrate how `String.format()` allows us to format strings with placeholders and control the appearance of numeric values, including specifying minimum widths and precision for floating-point numbers. Example-2The method supports various data types and formats them into a string type. Let's see an example. File Name: FormatExample2.java Output: 101 Amar Singh 101.000000 65 c Explanation: str1 formats an integer using %d, resulting in the string "101". str2 formats a string using %s, resulting in "Amar Singh". str3 formats a float using %f, resulting in "101.000000". str4 formats an integer as hexadecimal using %x, resulting in "65" (101 in hexadecimal). str5 formats a character using %c, resulting in "c". These examples demonstrate how different data types can be formatted using Java's `String.format()` method, providing versatility in formatting output according to your needs. Example-3Apart from formatting, we can set width, padding etc. of any value. Let's see an example where we are setting width and padding for an integer value. File Name: FormatExample3.java Output: 101 | 101| |101 | | 101| |0000000101| Explanation: str1 formats an integer using %d, resulting in the string "101". str2 formats an integer with a minimum width of 10 characters, right-aligned, resulting in "| 101|". str3 formats an integer with a minimum width of 10 characters, left-aligned, resulting in "|101 |". str4 formats an integer with a space before positive numbers, resulting in "| 101|". str5 formats an integer with a minimum width of 10 characters, filled with leading zeroes, resulting in "|0000000101|". These examples demonstrate various formatting options available in Java's String.format() method, allowing you to control the appearance of integers within strings. Java String Format SpecifiersFormat specifiers in Java's String.format() method allow you to control how data is displayed within a formatted string. Here are some common use cases for format specifiers: Formatting Numbers: %d: Formats an integer number. %f: Formats a floating-point number. %e, %E: Formats a floating-point number in scientific notation. %x, %X: Formats an integer number in hexadecimal. %o: Formats an integer number in octal. Output: Integer: 42, Float: 3.14 Formatting Strings: %s: Formats a string. Output: Hello, Alice! Formatting Booleans: %b: Formats a boolean value. Output: Is Admin: true Formatting Characters: %c: Formats a character. Output: Grade: A Specifying Width and Precision: We can specify the minimum width and precision of the formatted output. Output: Value: 123 Date and Time Formatting (using %t):%t followed by a conversion character formats date and time values. Conversion characters include: %tA: Full name of the day of the week. %tB: Full name of the month. %td: Day of the month (2-digit). %tm: Month (2-digit). %tY: Year (4-digit). %tH: Hour of the day (24-hour format). %tM: Minute. %tS: Second. Output: Today's date is Sunday, 06 February 2024 These are just a few examples of how format specifiers can be used in Java's String.format() method. They provide a powerful mechanism for formatting data dynamically within strings. Other Features of format() MethodTo specify width and precision: We can specify a minimum width and precision in the formatted output. Specifying the Argument Index: We can specify the index of the arguments that we want to sort. Local support: We can specify a location to apply local policy-specific rules. Why String.format() method in Java?Readability: Improves the readability of your code by separating the format from the data. Localization: Facilitates localization by allowing the user to easily convert formats based on locality. Dynamic Formatting: Enables dynamic formatting of a string based on runtime data. ConclusionThe String.format() method in Java provides a simple way to create a sorted string with placeholders. By using format specifiers and arguments, we can easily create complex textual output. Whether we are creating simple messages or formatting complex data, String.format() gives you the flexibility and readability we need. Next TopicJava String getBytes() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India