Site icon TestingDocs.com

Java String format() method with Examples

Overview

In this post, we will learn about Java String format() method with examples. String format() method is used to format strings in specified formats. It is the common way of formatting strings in Java language.

String format() Syntax

The method is a static overloaded method that is defined in the String class. The method might throw an IllegalFormatException if the specified format string is of illegal syntax.

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

Basic Example

Format string and double value:

try {
	String name= "Mark John";
	double cost = 34.99;
	System.out.println("Bill Amount Slip");
	System.out.println(String.format("Name: %30s", name));
	System.out.println(String.format("Total Cost $:
 %20.4f", cost));
	}catch(Exception e) {
	    System.out.println("Error"+ e.getMessage());
	}

For strings we have used %s format specifier. The number indicates the width of the string.
For floating point numbers we have used %f format specifier.
%20.4f prints the four numbers after the decimal point.

Display Formatted Table Example

The following Java program uses the String format() method to display the database table on to the console output window in Eclipse IDE.

https://www.testingdocs.com/display-data-from-oracle-database-table-using-jdbc/

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version