The program below is self-explanatory. It shows how to format a string in Java using the format method of the String class and System.out.printf. Enter the program below in Eclipse and observe what it does. You can use this page as a reference for formatting strings in future assignments.
import java.util.Date;
public class StringFormat{
public static void main(String args[]){
String formattedString = String.format("Order with OrdId : %d and Amount: %d is missing", 40021, 3000);
System.out.println(formattedString);
System.out.printf("Order with OrdId : %d and Amount: %d is missing \n", 40021, 3000);
String str = String.format("Hello %s", "Raj");
System.out.println(str);
str = String.format("Today is %tD", new Date());
System.out.println(str);
Date today = new Date();
System.out.printf("Date in dd/mm/yy format %td/%tm/%ty %n", today,today,today );
System.out.printf("Today is %tB %te, %tY %n", today,today,today,today);
System.out.printf("Amount : %08d %n" , 221);
System.out.printf("positive number : +%d %n", 1534632142);
System.out.printf("negative number : -%d %n", 989899);
System.out.printf("%f %n", Math.E);
System.out.printf("%.3f %n", Math.E);
System.out.printf("%8.3f %n", Math.E);
System.out.printf("Total %,d messages processed today", 10000000);
}
}
Format Code |
Description |
%s |
prints the string with no changes |
%15s |
prints the string as it is. Strings less than 15 characters will be padded on the left. |
%-6s |
prints the string as it is. Strings less than 6 characters will be padded on the right. |
%.8d |
prints up to 8 characters of the string. |
Format Code |
Description |
%d |
prints the integer with no changes |
%5d |
prints the integer as it is. Numbers with fewer than 5 digits will be padded on the left. |
%-5d |
prints the integer as it is. Numbers with fewer than 5 digits will be padded on the right. |
%05d |
prints the integer as it is. Numbers with fewer than 5 digits will be padded on the left with zeroes. |
%.2d |
prints up to 2 digits of the integer. |