How to Format Strings in Java
Page Last Updated: May 2014
Formatting strings in Java has always been a problem for developers because the basic System.out.println() method doesn’t support formatting of Strings while displaying the result on screen. Formatted Strings not only display the String content but it also displays the content in your specified sequence. For instance, when displaying large numbers like 100, 0000, 0000, it also displays the comma and while displaying decimal numbers, it prints numbers using proper decimal places like “134.43” as required. The need for formatted String is generally required in the modern GUI application. Java also has good formatting support for other types like Double, Integers and Date.
Learn Java from scratch through a course at Udemy.com
Java consists of two methods of formatting the Strings:
- format() method in java.lang.String class.
- printf() method in PrintStream class.
Using format() method:
The format method is a static method. It takes three arguments as input and returns a formatted String.
Syntax:
public static String format(String format, Object… args)
public static String format(Locale l, String format, Object… args)
- “Local l” is the locale applied during formatting. However, if it is null the localization isn’t applied.
- “format” contains the string you want formatted.
- “args” is the parameter referenced by format specifiers in the format String. If the arguments are more than the format specifiers, the extra arguments are ignored. Arguments can vary and may be zero.
Learn more about Java through a tutorial at Udemy.com
Exceptions Thrown by the method:
- IllegalFormatException: The exception is thrown due to illegal syntax or if an incompatible format specifier with respect to given arguments is given.
- NullPointerException: This exception is thrown when the String argument passed is null.
Simple Example of format():
“Local l”value is specified as “France” and the comma as written in the France number system will replace the decimal point.
class Demo
{
public static void main(String[] args)
{
System.out.format(Locale.FRANCE, "The value of the float " + "variable is %f ",
10.3242342);
Output:
The value of the float variable is 10,324234.
Formatting Instructions
String.format “%[argument number] [flags] [width] [.precision] type”
- %: This special character denotes the start of formatting instructions. String.format() method supports multiple occurrence of “%” character in a single formatting String.
- “argument number”: It specifies the corresponding argument in formatting.
- “flags”: A special instruction used to print String specific formats such as flags as “;” and to print a semicolon in the output.
- “width”: Gives you the option to output the minimum number of characters. If the number is larger than the width, the full number is displayed. Otherwise, it’s padded with zero.
- “precision”: This is used for printing the float point format String. It helps to specify the number of decimal values the floating number should display.
- “type”: A mandatory option. It’s always specified last and specifies the type of the parameter being formatted. For instance, “%d” is written for integer values.
Learn more about the fundamentals of Java through a tutorial at Udemy.com
Example: format(“%,6.3f”,1246.120)
Simple rules of String Formatting:
- %s: Will print the string with no change.
- %15s: Prints fifteen characters. If the character count is less than 15, the output is padded on the left.
- %-6s: Prints 6 characters as-is. If the string is less than 6 characters, the output is padded on the right.
- %.8s: Prints a maximum eight characters.
For Example:
class Test
{
public static void main (String[] args) throws.lang.Exception
{
//String is passed in the format function
String str = String.format("Hello %s", "Jack.Where is Jill?");
System.out.println(str);
String str1 = String.format("Hello %15s", "Jack.Where is Jill?");
System.out.println(str1);
String str2 = String.format("Hello %.6s", "Jack.Where is Jill?");
System.out.println(str2);
}
}
Output:
Hello Jack.Where is Jill?
Hello Jack.Where is Jill?
Hello Jack.W
The String is passed in format function which returns a formatted String. Note that the format function does not print the value on the screen.
Rules for Formatting Float Values
- %f: Number will be printed as it is.
- %10f: Will print the ten digits. If the digits are less than ten, the output is padded left.
- %.6f: Maximum of 6 digits will be printed.
- %8.3f: three decimal digits will be printed.
Example
class Sample
{
public static void main (String[] args) throws java.lang.Exception
{
//Passing float value in the function.
String s = String.format("%12.8f %.15f", 12.34567890123,9.1098765432);
System.out.println(s);
String str1 = String.format("%-1.5f %.10f", 12.34567890123,9.1098765432);
System.out.println(str1);
String str2 = String.format("%-8.5f %.20f", 12.34567890123,9.1098765432);
System.out.println(str2);
}
}
Output
12.34567890 9.109876543200000
12.34568 9.1098765432
12.34568 9.10987654320000000000
Formatting the Date: The format method provides an excellent way of formatting the date in any standard form. The variable holding the date is passed in the format function of java.text.SimpleDataFormat class whose object specifies the format of the date.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.SimpleDateFormat;
class DateFormat {
public static void main(String args[]) {
// to get today's date in Java
Date today = new Date();
System.out.println("Unformatted Date : " + today);
//formatting Date in Java in dd-MM-yyyy format
SimpleDateFormat DATE_F = new SimpleDateFormat("dd-MM-yyyy");
String dat = DATE_F.format(today);
System.out.println("Formatted Date in dd-MM-yyyy : " + dat);
//formatting Date in Java in dd/MM/yy format
DATE_F = new SimpleDateFormat("dd/MM/yy");
dat = DATE_F.format(today);
System.out.println("Another Format Date in dd/MM/yy : " + dat);
//formatting Date in Java in dd-MM-yy:HH:mm:SS format
DATE_F = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
dat = DATE_F.format(today);
System.out.println("Another Format Date in dd-MM-yy:HH:mm:SS : " + dat);
}
}
Output:
Unformatted Date : Thu May 15 05:18:58 GMT 2014
Formatted Date in dd-MM-yyyy : 15-05-2014
Another Format Date in dd/MM/yy : 15/05/14
Another Format Date in dd-MM-yy:HH:mm:SS : 15-05-14:05:18:160
Using printf(): This method is similar to printf used in C programming. It’s used similar to a replacement of System.out.println(). Unlike the format() method, the printf method prints String on screen.
Syntax 1:
public PrintStream format(String format, Object… args)
“format” is the format String which contains the format specifiers specifying how the argument will be formatted and “args” is the list of variables to be printed. “Object… args” notion is called varargs which means that the arguments may vary.
Example:
class StringFormat
{
public static void main(String[] args)
{
System.out.printf("Integer : %d\n",15);
System.out.printf("Floating number with 4 decimal digits: %.4f\n",1.123123123123);
System.out.printf("Floating number with 6 decimal digits: %.6f\n",1.123123123123);
System.out.printf("String: %s, integer: %d, float: %.6f", "Hello World",55,9.1234567);
}
}
Output:
Integer : 15
Floating number with 4 decimal digits: 1.1231
Floating number with 6 decimal digits: 1.123123
String: Hello World, integer: 55, float: 9.123457
The Strings, integer and floating values are directly passed to the printf() and the formatted output is displayed on the screen.
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.