Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Friday, October 30, 2015

String Formatting in Java

You can use the C-style printf() (print formatted) method that was introduced in Java 5.

The method printf() uses string-formatting flags to format strings. It is quite similar to the printf() function provided in the library of the C programming language. The printf() method is provided as part of the PrintStream class. Here is its signature:

PrintStream printf(String format, Object... args)

Format Specifiers

The template of format specifiers in the printf() method:

%[flags][width][.precision]datatype_specifier

Flags are single-character symbols that specify characteristics such as alignment and filling character.
The precision field specifies the number of precision digits in output string.

the data type specifier indicates the type of expected input data.

FormattedTable.java

package com.appfworks.string;

/**
* Created by suresh on 30/10/15.
*/
// This program demonstrates the use of format specifiers in printf
class FormattedTable {
static void line() {
System.out.
println("-----------------------------------------------------------------");
}
static void printHeader() {
System.out.printf("%-15s \t %s \t %s \t %s \n",
"Player", "Matches", "Goals", "Goals per match");
}
static void printRow(String player, int matches, int goals) {
System.out.printf("%-15s \t %5d \t\t %d \t\t %.1f \n",
player, matches, goals, ((float)goals/(float)matches));
}
public static void main(String[] str) {
FormattedTable.line();
FormattedTable.printHeader();
FormattedTable.line();
FormattedTable.printRow("Demando", 100, 122);
FormattedTable.printRow("Mushi", 80, 100);
FormattedTable.printRow("Peale", 150, 180);
FormattedTable.line();
}
}


No comments:

Post a Comment