Java String format() method
format() method returns a formatted String based on the given locale,specified format and arguments.
Syntax:
public static String format(String format , Object… args)
Parameter:
locale : It specifies locale value to be applied on the format() method.
format: It specifies the format of the output String
args : It specifies the number of arguments for the format String.It may be zero or more
Returns:
It returns a formatted String
Java String format() Example 1
public class JavaStringFormatEx1 { public static void main(String args[]) { String s1 = "Tutorial And Example"; // Concatenation of two strings String str1 = String.format("Welcome to %s", s1); // Output is given upto 11 decimal places String str2 = String.format("value is %.11f", 75.23456); System.out.println(str1); System.out.println(str2); } }
Output:
Welcome to Tutorial And Example value is 75.23456000000 value is 47.65734000
Java String format() Example 2
public class JavaStringFormatEx2 { public static void main(String args[]) { String s1="Nitish"; String f1=String.format("name is %s",s1); String f2=String.format("value is %f",54.15789); String f3=String.format("value is %54.15f",54.15789); System.out.println(f1); System.out.println(f2); System.out.println(f3); } }
Output:
name is Nitish value is 54.157890 value is 54.157890000000000
Java String format() Example 3
public class JavaStringFormatEx3 { public static void main(String[] args) { String s1 = String.format("%d", 101); // Integer value String s2 = String.format("%f", 101.00); // Float value String s3 = String.format("%x", 101); // Hexadecimal value String s4 = String.format("%c", 'N'); // Char value String s5 = String.format("%s", "Roy Nitish Nk"); // String value System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); System.out.println(s5); } }
Output:
101101. 00000065 N Roy Nitish Nk
Java String format() Example 4
public class JavaStringFormatEx4 { public static void main(String[] args) { String str1 = String.format("%d", 101); String str2 = String.format("|%10d|", 101); // Specifying length of integer String str3 = String.format("|%-10d|", 101); // Left-justifying within the specified width String str4 = String.format("|% d|", 101); String str5 = String.format("|%010d|", 101); // Filling with zeroes System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); System.out.println(str5); } }
Output:
101 101 101 101 0000000101