Java string format with parameters

Java String format() method explained with examples

Java String format() method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. In this tutorial, we will see several examples of Java String format() method.

Syntax of format() method

public static String format(Locale l, String format, Object. args)

Returns a formatted string using the specified locale, format string, and arguments.

public static String format(String format, Object. args)

Returns a formatted string using the specified format string and arguments.

A Simple Example of Java String format() method

My String is just a string My String is 12.121000

Java String format() example of concatenating arguments to the string

We can specify the argument positions using %1$, %2$. format specifiers. Here %1$ represents first argument, %2$ second argument and so on.

My String is: cool string, cool string and 88

As you can see that how we have passed the string “cool string” twice in the format() method using the argument positions format specifiers.

Left padding the string using string format()

In this example, we are left padding a number with 0’s and converting the number to a formatted String. In the above example we have formatted the float numbers and Strings and in this example we are formatting an integer. The important point to remember is that the format specifiers for these are different.
%s – for strings
%f – for floats
%d – for integers

Displaying String, int, hexadecimal, float, char, octal value using format() method

In the following example, we are using different format specifiers to display values of different types. Here we have shown few examples of how an integer value can be converted into an octal or hexadecimal value using format() method. After this example, we have shared a list of available format specifiers.

Java String format method example

Output:

Java String Format Specifiers

%c – Character
%d – Integer
%s – String
%o – Octal
%x – Hexadecimal
%f – Floating number
%h – hash code of a value

Читайте также:  What can you create using java

References:

Источник

String.format()

String.format() is a powerful tool in Java that allows you to format strings in a variety of ways.
You can use it to format numbers, dates, currencies, and other values. You can even use it to create complex strings with multiple lines and placeholders.
Syntax
String.format() accepts two arguments.
1. A string that you want to format.
This string can be anything, but it must contain what are called format specifiers.
Format specifiers are placeholders for variables that you want to insert into the string.

Placeholders are denoted by a % symbol followed by a pre-defined letters. An example of a placeholder is %s , which is used for string values.
2. Values to be inserted into the placeholders in the format string.

String.format() returns a string with placeholders replaced with corresponding values.
String.format() example
Below is a simple example to understand the usage of String.format() .

String language = "java"; String unfmt = "Learning %s language"; String fmt = String.format(unfmt, language); System.out.print(fmt);

Here, the placeholder %s in the first argument is replaced with the second argument value.
This prints

Understanding java language

Formatting multiple values
We can substitute values from multiple variables in a string at once as well.
Also, these values can be of different types as shown below

int number = 123; double amount = 123.45; String s = "abc"; String fmt = String.format("Number is %d, " + "String is %s, " + "Amount is %f", number, s, amount); System.out.println(fmt);

In this example, we replace three different values in a single string.
All these values are of different data types and the string produced by format() is

Number is 123, String is abc, Amount is 123.450000

Notice that it appended 0’s after double value, which is not required.
Also, at times you might want to display values only till specific decimal values.
With format() , you can define the precision of decimal values using point( . ) after % , followed by the number of digits to be displayed such as %.2f . Example,

double amt = 123.45; // remove trailing zeroes System.out.println(String.format("%.2f", amt)); double large = 123.46564; // display only 3 decimal places System.out.println(String.format("%.3f", large));

Below is a list of format options that can be used with String.format()

Option Description
b, B For formatting boolean values, true or false .
If the value to be formatted is null, it returns false .
h, H For formatting to hexadecimal.
s, S For formatting values of type string.
d For formatting integer values.
f For formatting decimal or floating point values.
x, X For formatting to hexadecimal but the value to be formatted should be an integer.
o For formatting to octal.
n Adding platform specific line-separator
t, T For formatting date/time values.

Lower and upper case letters return result in corresponding case.
This list can be found here .

Formatting hexadecimal values
If the value to be converted to hexadecimal is a string, then use h , H flags.
If the value to be converted to hexadecimal is an integer, then use x or X flags. Examples,

System.out.println( String.format("123 in hex is %x", 123)); System.out.println( String.format("12g in hex is %h", "12g")); System.out.println( String.format("12g in hex is %H", "12g"));

123 in hex is 7b
12g in hex is be66
12g in hex is BE66

Читайте также:  String to function name in javascript

Formatting to octal
Use o flag with String.format() to format a value to octal. Example,

System.out.println( String.format("123 in octal is %o", 123));

Formatting dates
%t along with D flag is used to format date. The value should be of type java.util.Date .
D flag will format the date in mm/dd/yy format. To convert to other formats, use Y , m and d flags for year, month and day, as shown below

Date d = new Date(); System.out.println(String.format("%tD", d)); System.out.println(String.format("%tY-%tm-%td", d,d,d));

To print the last two digits of year, y flag is used.
Formatting time
%t along with T flag is used to format time. The value should be of type java.util.Date .
T flag will format the time in hh:mm:ss format. To convert to other formats, use H , M and S flags for hour, minute and second, as shown below

Date d = new Date(); System.out.println(String.format("%tT", d)); System.out.println(String.format("%tH:%tM", d,d,d));

Padding spaces and zeroes
Sometimes you might want to display a value between fixed widths while the value to be displayed is lesser than the width.
In such cases, you need to add empty spaces or 0s before the values. This is called padding.
String.format() provides support to pad a value with both spaces and 0s simply by providing the width before the appropriate flag as shown below

int number = 123; System.out.println( String.format("Value padded with spaces %5d", number)); System.out.println( String.format("Value padded with zeroes %05d", number));

Value padded with spaces 123
Value padded with zeroes 00123

Local specific formatting
With String.format() , you can format values specific to a locale by providing locale as the first argument.
There is an overloaded format() method which takes 3 arguments as below

public static String format(Locale l, String format, Object… args)

double amount = 123.4534; String fmt = String.format("Amount in default locale " + " is %.2f ", amount); System.out.println(fmt); fmt = String.format(Locale.FRENCH, "Amount in french locale is %.2f ", amount); System.out.println(fmt);

Amount in default locale is 123.45
Amount in french locale is 123,45

Look, the second value is formatted in french locale, since we have , in place of .
Pass values from array
If there are multiple values to be formatted in a single string, then the argument list can become too long as in the below example

int n1 = 47, n2 = 64, n3 = 96; String text = "Result"; System.out.println( String.format("%s: Hex: %x, Octal: %o, " + " Decimal: %d", text, n1, n2, n3));

This, not only becomes complex but more error prone.

To solve this, format() also accepts an array in place of multiple values as shown below

int n1 = 47, n2 = 64, n3 = 96; String text = "Result"; // define an array Object[] arr = ; System.out.println( String.format("%s: Hex: %x, Octal: %o, Decimal: %d", arr));

Array values are replaced in the order of their indexes. That is, first placeholder will be replaced with first array element and so on.
So, you need to be careful with the order of array elements.

Читайте также:  Have multiple classes css

Another way is to define the index of array element along with placeholder using position and $ symbol with format symbol such as %2$s , which references second element. Example,

int n1 = 47, n2 = 64, n3 = 96; String text = "Result"; Object[] arr = ; System.out.println( String.format("%1$s: Hex: %2$x, Octal: %3$o, " + " Decimal: %4$d", arr));

Источник

Java String format() method explained with examples

Java String format() method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. In this tutorial, we will see several examples of Java String format() method.

Syntax of format() method

public static String format(Locale l, String format, Object. args)

Returns a formatted string using the specified locale, format string, and arguments.

public static String format(String format, Object. args)

Returns a formatted string using the specified format string and arguments.

A Simple Example of Java String format() method

My String is just a string My String is 12.121000

Java String format() example of concatenating arguments to the string

We can specify the argument positions using %1$, %2$. format specifiers. Here %1$ represents first argument, %2$ second argument and so on.

My String is: cool string, cool string and 88

As you can see that how we have passed the string “cool string” twice in the format() method using the argument positions format specifiers.

Left padding the string using string format()

In this example, we are left padding a number with 0’s and converting the number to a formatted String. In the above example we have formatted the float numbers and Strings and in this example we are formatting an integer. The important point to remember is that the format specifiers for these are different.
%s – for strings
%f – for floats
%d – for integers

Displaying String, int, hexadecimal, float, char, octal value using format() method

In the following example, we are using different format specifiers to display values of different types. Here we have shown few examples of how an integer value can be converted into an octal or hexadecimal value using format() method. After this example, we have shared a list of available format specifiers.

Java String format method example

Output:

Java String Format Specifiers

%c – Character
%d – Integer
%s – String
%o – Octal
%x – Hexadecimal
%f – Floating number
%h – hash code of a value

References:

Источник

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