Phương thức printf() cho phép định dạng đầu ra tới java.io.PrintStream hoặc java.io.PrintWriter. Các lớp này cũng có phương thức format() cho cùng kết quả, nên kiến thức về printf() áp dụng cho format().
Cú pháp
System.out.printf("format-string" [, arg1, arg2, ... ]);
Ví dụ 1
import java.io.PrintStream;
public class PrintfTest1 {
public static void main(String[] args) {
int i = 1234;
System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x\n", i);
String str = "Tutorials Point";
System.out.printf("%15s", str);
}
}
Kết quả
Decimal: 1,234 Octal: 2322 Hex: 4d2 Tutorials Point
Ví dụ 2
public class PrintfTest2 {
public static void main(String[] args) {
String name = "Adithya";
int age = 30;
System.out.format("%-10s - %4d\n", name, age);
}
}
Kết quả
Adithya - 30