String format java format specifiers

Java String format

In this article we show how to format strings in Java.

In Java, we have methods for string formatting. Another way to dynamically create strings is string building.

The System.out.printf , System.out.format , and formatted methods can be used to format strings in Java. They work the same. These three methods write a formatted string to the output stream using the specified format string and arguments. If there are more arguments than format specifiers, the extra arguments are ignored.

%[argument_index$][flags][width][.precision]conversion

The format specifiers for general, character, and numeric types have this syntax.

%[argument_index$][flags][width]conversion

This is the syntax for types which are used to represents dates and times.

The format specifiers begin with the % character and end with a 1 or 2 character conversion that specifies the kind of formatted output being generated. The optional items are placed between the square brackets.

The argument_index is a decimal integer indicating the position of the argument in the argument list. The flags is a set of characters that modify the output format. The set of valid flags depends on the conversion. The width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

The precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. The required conversion is a character indicating how the argument should be formatted.

Java String format methods

We use the three methods to format a simple message.

package com.zetcode; public class FormatMethods < public static void main(String[] args) < String name = "John Doe"; String occupation = "gardener"; String txt = "%s is a %s"; String msg = txt.formatted(name, occupation); System.out.println(msg); System.out.format("%s is a %s\n", name, occupation); System.out.printf("%s is a %s%n", name, occupation); >>

We build the same string three times.

String name = "John Doe"; String occupation = "gardener"; String txt = "%s is a %s"; String msg = txt.formatted(name, occupation);

The formatted method is an instance method.

System.out.format("%s is a %s\n", name, occupation); System.out.printf("%s is a %s%n", name, occupation);

The format and printf methods are static.

$ java FormatMethods.java John Doe is a gardener John Doe is a gardener John Doe is a gardener

Java String format specifiers

Next we use two basic format specifiers.

package com.zetcode; public class Conversions < public static void main(String[] args) < System.out.format("There are %d %s.%n", 5, "pencils"); System.out.printf("The rock weighs %f kilograms.%n", 5.345); >>

In this program, we format two simple sentences.

System.out.format("There are %d %s.%n", 5, "pencils");

In this code line, we have three format specifiers. Each specifier starts with the % character. The d specifier formats integer values. The s specifier expects string values. The %n outputs a platform-specific line terminator; it does not require an argument.

System.out.printf("The rock weighs %f kilograms.%n", 5.345);

The f formats a floating point value as a decimal value. The System.out.printf works the same as the System.out.format .

$ java Conversions.java There are 5 pencils. The rock weighs 5.345000 kilograms.

Java String format argument index

In the next example, we work with argument indexes.

package com.zetcode; import java.time.LocalDateTime; public class IndexPosition < public static void main(String[] args) < int x = 12; int y = 32; int z = 43; LocalDateTime dt = LocalDateTime.now(); System.out.format("There are %d apples, %d oranges and " + "%d pears%n", x, y, z); System.out.format("There are %2$d apples, %3$d oranges and " + "%1$d pears%n", x, y, z); System.out.format("Year: %tY, Month: %>

The example uses argument index to refer to variables included the list of arguments.

System.out.format("There are %d apples, %d oranges and " + "%d pears%n", x, y, z);

If we do not specify the index, the variables automatically match the specifiers. The d specifier formats an integer value as a decimal value.

System.out.format("There are %2$d apples, %3$d oranges and " + "%1$d pears%n", x, y, z);

The 1$ referes to the x variable, the 2$ referes to the y variable and the 3$ refers to the z variable.

System.out.format("Year: %tY, Month: %
$ java IndexPosition.java There are 12 apples, 32 oranges and 43 pears There are 32 apples, 43 oranges and 12 pears Year: 2022, Month: 10, Day: 17

Java String format flag

The flag modifies the format in a specific way. There are several flags available. For instance, the + flag requires the output to include a positive sign for all positive numbers.

package com.zetcode; public class Flags < public static void main(String[] args) < System.out.format("%+d%n", 553); System.out.format("%010d%n", 553); System.out.format("%10d%n", 553); System.out.format("%-10d%n", 553); System.out.format("%d%n", -553); System.out.format("%(d%n", -553); >>

The example presents a few flags of the string format specifier.

The 0 flag will cause the output to be padded with leading zeros to the minimum field width. Our number has three digits. The minimum width is 10. Therefore, we have 7 leading zeros in the output.

Without the 0 flag, the number is right aligned.

The - flag will cause the number to be left aligned.

System.out.format("%d%n", -553); System.out.format("%(d%n", -553);

By default, negative numbers have a minus sign. If we use the ( flag, the negative values will be put inside round brackets. (This is used in accounting.)

$ java Flags.java +553 0000000553 553 553 -553 (553)

Java String format width

The width field is the minimum number of characters to be written to the output. It cannot be used together with the line separator.

package com.zetcode; public class WidthSpecifier < public static void main(String[] args) < System.out.println(1); System.out.println(16); System.out.println(1655); System.out.println(16567); System.out.println(166701); System.out.format("%10d%n", 1); System.out.format("%10d%n", 16); System.out.format("%10d%n", 1655); System.out.format("%10d%n", 16567); System.out.format("%10d%n", 166701); >>

First, we print five numbers without specifying the field width. The width of the output is equal to the number of the characters being displayed. In the second case, we have a field width of 10. Each of the 5 outputs has a minimum length of 10 characters. The numbers are right aligned.

Number 10 states that the string output must have at least ten characters.

$ java WidthSpecifier.java 1 16 1655 16567 166701 1 16 1655 16567 166701

We can see that in the second case the numbers are right aligned.

Java String format precision

The precision field has different meaning for different conversions. For general argument types, the precision is the maximum number of characters to be written to the output.

package com.zetcode; public class PrecisionSpecifier < public static void main(String[] args) < System.out.format("%.3g%n", 0.0000006); System.out.format("%.3f%n", 54.34263); System.out.format("%.3s%n", "ZetCode"); >>

The precision specifier is demonstrated on three different outputs.

System.out.format("%.3g%n", 0.0000006);

If the g conversion is used, then the precision is the total number of digits in the resulting magnitude after rounding.

System.out.format("%.3f%n", 54.34263);

For floating point values, the precision is the number of digits after the decimal separator.

System.out.format("%.3s%n", "ZetCode");

For strings, it is the maximum number of printed characters. Only three characters out of seven are printed to the console.

$ java PrecisionSpecifier.java 6.00e-07 54.343 Zet

Java String format numbers

The next example formats numeric data.

package com.zetcode; public class FormatNumbers < public static void main(String[] args) < System.out.format("%d%n", 12263); System.out.format("%o%n", 12263); System.out.format("%x%n", 12263); System.out.format("%e%n", 0.03452342263); System.out.format("%d%%%n", 45); >>

The example demonstrates the standard formatting specifiers for numbers.

The d conversion specifier will turn an integer value into a decimal value.

The o conversion specifier will format the number into the octal base.

With the x specifier, the result is formatted as a hexadecimal integer.

System.out.format("%e%n", 0.03452342263);

Using the e specifier, the number is printed in a scientific notation.

The %% characters are used to print a percent sign.

$ java FormatNumbers.java 12263 27747 2fe7 3.452342e-02 45%

Java String format date and time

Finally, we format date and time data.

package com.zetcode; import java.time.LocalDateTime; public class FormatDateTime < public static void main(String[] args) < LocalDateTime ldt = LocalDateTime.now(); System.out.format("%tF%n", ldt); System.out.format("%tD%n", ldt); System.out.format("%tT%n", ldt); System.out.format("%1$tA, %1$tb %1$tY%n", ldt); System.out.format("%1$td.%1$tm.%1$tY%n", ldt); >>

The example demonstrates the standard formatting specifiers for dates. The conversion part of the date and time format string starts with the t character.

This line prints a date in a complete ISO 8601 format, as a result of the tF conversion.

System.out.format("%1$td.%1$tm.%1$tY%n", c);

Using these format specifiers, we print a date in the form that is used in Slovakia. The parts are separated by the dot character and the day precedes the month and the month precedes the year. All three format specifiers refer to the c variable.

$ java FormatDateTime.java 2022-10-17 10/17/22 11:30:18 Monday, Oct 2022 17.10.2022

Java localized String format

We can pass the locale to the formatting methods.

package com.zetcode; import java.time.LocalDate; import java.util.Locale; public class Localized < public static void main(String[] args) < double val = 12_568_120.214; LocalDate now = LocalDate.now(); System.out.printf("%f%n", val); System.out.printf(Locale.FRENCH, "%f%n", val); System.out.printf("%tA%n", now); System.out.printf(Locale.FRENCH, "%tA%n", now); >>

In the example, we print values in English and French locales.

$ java Localized.java 12568120.214000 12568120,214000 Monday lundi

In this article we have formatted strings in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Formatting

Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.

Note: The only PrintStream objects you are likely to need are System.out and System.err . (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter , not PrintStream .

Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided:

  • print and println format individual values in a standard way.
  • format formats almost any number of values based on a format string, with many options for precise formatting.

The print and println Methods

Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:

Here is the output of Root :

The square root of 2 is 1.4142135623730951. The square root of 5 is 2.23606797749979.

The i and r variables are formatted twice: the first time using code in an overload of print , the second time by conversion code automatically generated by the Java compiler, which also utilizes toString . You can format any value this way, but you don't have much control over the results.

The format Method

The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.

Format strings support many features. In this tutorial, we'll just cover some basics. For a complete description, see format string syntax in the API specification.

The Root2 example formats two values with a single format invocation:

The square root of 2 is 1.414214.

Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are:

  • d formats an integer value as a decimal value.
  • f formats a floating point value as a decimal value.
  • n outputs a platform-specific line terminator.

Here are some other conversions:

  • x formats an integer as a hexadecimal value.
  • s formats any value as a string.
  • tB formats an integer as a locale-specific month name.

There are many other conversions.

Except for %% and %n , all format specifiers must match an argument. If they don't, an exception is thrown.

In the Java programming language, the \n escape always generates the linefeed character ( \u000A ). Don't use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n .

In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here's an example, Format , that uses every possible kind of element.

3.141593, +00000003.1415926536

The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements.

Elements of a Format Specifier.

The elements must appear in the order shown. Working from the right, the optional elements are:

  • Precision. For floating point values, this is the mathematical precision of the formatted value. For s and other general conversions, this is the maximum width of the formatted value; the value is right-truncated if necessary.
  • Width. The minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.
  • Flags specify additional formatting options. In the Format example, the + flag specifies that the number should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include - (pad on the right) and , (format number with locale-specific thousands separators). Note that some flags cannot be used with certain other flags or with certain conversions.
  • The Argument Index allows you to explicitly match a designated argument. You can also specify < to match the same argument as the previous specifier. Thus the example could have said: System.out.format("%f, %

Источник

Читайте также:  Html div css styling
Оцените статью