String format​ method in java with example - Internal Implementation

String format​ method in java:

String format method is used to format the string in the specified format. This method can be used as String output format by passing multiple arguments because the second parameter is the variable-arguments(Var-Args). Recommend to read in-depth usage of Var-Args in Java. We can pass any type of object here such as String, Float, Double etc together. You will find the examples on each in this course.

This format method is introduced in java 1.5 version and it is overloaded and static methods


String format​ Method Example in java


format​ method Syntax: 

// Takes default locale 
public static String format​(String format, Object... args)
//Takes passed locale instead of default locale value
public static String format​(Locale l, String format, Object... args)



Parameters:

    
format - A format string
    
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behavior on a null argument depends on the conversion.

l - The locale to apply during formatting. If l is null then no localization is applied.

Formatter: 

Formatter is an interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, BigDecimal, and Calendar are supported. Limited formatting customization for arbitrary user types is provided through the Formattable interface. 

Returns:

    A formatted string

Throws:

    IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.

String format​ Method Example in java:

Program to format the string in different specified formats such as String, Numeric, Additional spaces. format method takes by default locale.
The locale always used is the one returned by Locale.getDefault(Locale.Category) with FORMAT category specified.

package examples.java.w3schools.string;

public class StringFormatExample {
public static void main(String[] args) {

String blogName = "Java-W3schools blog";

String format1 = String.format("String methods on website %s ", blogName);
System.out.println("String formatted value: " + format1);

// Float format
String format2 = String.format("String methods on website %f9 ", 12.345f);
System.out.println("Float formatted string value: " + format2);
}
}


Output:


The above program produces the below output.


String formatted value: String methods on website Java-W3schools blog 
Float formatted string value: String methods on website 12.3450009


String format​ Method Example with multiple arguments:



Example Program to format the string with multiple string arguments. We can pass String, Float values at once to the format method.
package examples.java.w3schools.string;

public class StringFormatExample {
public static void main(String[] args) {

String blogName = "Java-W3schools blog";
float worth = 15000.99f;

String value = String.format("Welcome to the famous %S with worth $%5f", blogName, worth);
System.out.println("Formatted String value: " + value);

}
}


Output:

The above program produces the below output.


Formatted String value: Welcome to the famous Java-W3schools blog with worth $15000.990234


Converting a String to Uppercase using format​ Method:

Example program to convert a lowercase String to Uppercase using format​ Method. Converting to uppercase is done using '%S'. Refer the below code.
  String blogName = "Java-W3schools";

String value = String.format("Welcome to the famous %S Blog", blogName);
System.out.println("Formatted String value: " + value);


Output:


The above code produces the below output. See the uppercase text in the output.
Formatted String value: Welcome to the famous JAVA-W3SCHOOLS Blog


Example program to make a number to 10 digits always: 



In this program, We will see how to make always a number to 10 digits if number is having 9 digits or below. This also can be achieved using format method.
  String value1 = String.format("Number %010d", 12345);
System.out.println("Formatted Number value 1: " + value1);

String value2 = String.format("Number %010d", 999);
System.out.println("Formatted Number value 2: " + value2);

String value3 = String.format("Number %010d", 7777777);
System.out.println("Formatted Number value 3: " + value3);

Output:


Observe the output always has 10 digits even though input is not having 10 digits in it.


Formatted Number value 1: Number 0000012345
Formatted Number value 2: Number 0000000999
Formatted Number value 3: Number 0007777777


When IllegalFormatException will be thrown:


Example Program to see how IllegalFormatException will be thrown and what is the scenario.

For the format method crucial is format that we declare whether it is %s, %S, %f or any valid format. Just guess what will happen if invalid format is passed.
 String value1 = String.format("Format %x ", "hello");

Here passed "%x" is the specified format but where 'x' is a invalid character as per the format rules for string type value.


Output:


A run-time exception is thrown stating x is not a string type.


Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2938)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2892)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.util.Formatter.format(Formatter.java:2609)
at java.base/java.lang.String.format(String.java:2897)
at w3schools/examples.java.w3schools.string.StringFormatExample.main(StringFormatExample.java:7)


String format​ method Internal Implementation:




The below code is the internal implementation. Internally, Formatter class does all the stuff what looks string format does.


format(String format, Object... args):


   public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}

Locale public static String format:


  public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}

Please post your questions in comment section. We will get you the right answers.


0 Comments