Java: String format(String format, Object… args) method

In this article, we will discuss formatting a string using String’s format() method

 

format(String format, Object… args) method: This String method is used to format a string using supplied or input arguments i.e.;

  • Format –> format of the string like (%s, %f, %n, %d)
  • Object –> actual string input to be formatted
  • Local –> if not provided, it uses default local, by invoking Locale.getDefault();

 

Method Signature:

public static String format(String format, Object… args);

public static String format(Locale locale, String format, Object… args);

 

Returns:

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

 

Throws:

  • NullPointerException: If the format passed is null
  • IllegalFormatException: If the syntax of format passed is illegal or incompatible with the given arguments or some other illegal conditions

 

Examples on format() method:

Sample Java program to get formatted string

StringFormatMethod.java

package in.bench.resources.string.methods;

public class StringFormatMethod {

	public static void main(String[] args) {

		// sample variable declarations
		String testString = "BenchResources";
		float testFloat = 141.236958f;

		// String formatting using string value and %s formatter
		String strFomrat1 = String.format("%s", testString);

		// String formatting using float value and %f formatter
		String strFomrat2 = String.format("%f", testFloat);

		// String formatting using float value and %3.2f formatter
		String strFomrat3 = String.format("%3.2f", testFloat);

		// printing formatted values
		System.out.println(strFomrat1);
		System.out.println(strFomrat2);
		System.out.println(strFomrat3);
	}
}

Output:

BenchResources
141.236954
141.24

 

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!

Java: String getBytes() method
Java: String equalsIgnoreCase(Object anObject) method