Format names in java

Java String Format Examples

Have you tried to read and understand Java’s String format documentation? I have and found it hard to understand. While it does include all the information, the organization leaves something to be desired.

This guide is an attempt to bring some clarity and ease the usage of string formatting in java.

Learn about string formatting in python? Check out this article.

2. String Formatting

Most common way of formatting a string in java is using String.format(). If there were a “java sprintf”, this would be it.

String output = String.format("%s = %d", "joe", 35);

For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.

System.out.printf("My name is: %s%n", "joe");

Create a Formatter and link it to a StringBuilder. Output formatted using the format() method will be appended to the StringBuilder.

StringBuilder sbuf = new StringBuilder(); Formatter fmt = new Formatter(sbuf); fmt.format("PI = %f%n", Math.PI); System.out.print(sbuf.toString()); // you can continue to append data to sbuf here.

3. Format Specifiers

Here is a quick reference to all the conversion specifiers supported.

Specifier Applies to Output
%a floating point (except BigDecimal) Hex output of floating point number
%b Any type “true” if non-null, “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Hex string.
Читайте также:  Python math prime numbers

3.1. Date and Time Formatting

Note: Using the formatting characters with “%T” instead of “%t” in the table below makes the output uppercase.

Flag Notes
%tA Full name of the day of the week, e.g. “ Sunday “, “ Monday “
%ta Abbreviated name of the week day e.g. “ Sun “, “ Mon “, etc.
%tB Full name of the month e.g. “ January “, “ February “, etc.
%tb Abbreviated month name e.g. “ Jan “, “ Feb “, etc.
%tC Century part of year formatted with two digits e.g. “00” through “99”.
%tc Date and time formatted with “ %ta %tb %td %tT %tZ %tY ” e.g. “ Fri Feb 17 07:45:42 PST 2017 “
%tD Date formatted as “ %tm/%td/%ty “
%td Day of the month formatted with two digits. e.g. “ 01 ” to “ 31 “.
%te Day of the month formatted without a leading 0 e.g. “1” to “31”.
%tF ISO 8601 formatted date with “ %tY-%tm-%td “.
%tH Hour of the day for the 24-hour clock e.g. “ 00 ” to “ 23 “.
%th Same as %tb.
%tI Hour of the day for the 12-hour clock e.g. “ 01 ” – “ 12 “.
%tj Day of the year formatted with leading 0s e.g. “ 001 ” to “ 366 “.
%tk Hour of the day for the 24 hour clock without a leading 0 e.g. “ 0 ” to “ 23 “.
%tl Hour of the day for the 12-hour click without a leading 0 e.g. “ 1 ” to “ 12 “.
%tM Minute within the hour formatted a leading 0 e.g. “ 00 ” to “ 59 “.
%tm Month formatted with a leading 0 e.g. “ 01 ” to “ 12 “.
%tN Nanosecond formatted with 9 digits and leading 0s e.g. “000000000” to “999999999”.
%tp Locale specific “am” or “pm” marker.
%tQ Milliseconds since epoch Jan 1 , 1970 00:00:00 UTC.
%tR Time formatted as 24-hours e.g. “ %tH:%tM “.
%tr Time formatted as 12-hours e.g. “ %tI:%tM:%tS %Tp “.
%tS Seconds within the minute formatted with 2 digits e.g. “00” to “60”. “60” is required to support leap seconds.
%ts Seconds since the epoch Jan 1, 1970 00:00:00 UTC.
%tT Time formatted as 24-hours e.g. “ %tH:%tM:%tS “.
%tY Year formatted with 4 digits e.g. “ 0000 ” to “ 9999 “.
%ty Year formatted with 2 digits e.g. “ 00 ” to “ 99 “.
%tZ Time zone abbreviation. e.g. “ UTC “, “ PST “, etc.
%tz Time Zone Offset from GMT e.g. “ -0800 “.
Читайте также:  Telegram bot edit message php

4. Argument Index

An argument index is specified as a number ending with a “ $ ” after the “ % ” and selects the specified argument in the argument list.

String.format("%2$s", 32, "Hello"); // prints: "Hello"

5. Formatting an Integer

With the %d format specifier, you can use an argument of all integral types including byte, short, int, long and BigInteger.

Default formatting:
String.format("%d", 93); // prints 93

Источник

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.

Источник

Оцените статью