Java printf() Example



In this source code example, we will demonstrate the usage of printf() method in Java with source code example. The method is part of the java.io.PrintStream class and provides String formatting similar to the printf() function in C.

Java printf() Example

The below example the usage of printf() method and String, Char, Boolean, Number, Float formatting:
import java.util.Date;
import java.util.Locale;

public class PrintfExamples {

    public static void main(String[] args) {

        printfNewLine();
        printfChar();
        printfString();
        printfNumber();
        printfDateTime();
        printfBoolean();
    }

    private static void printfNewLine() {
        System.out.printf("sourcecodeexamples%nline%nterminator");
    }

    private static void printfString() {
        System.out.printf("'%s' %n", "sourcecodeexamples");
        System.out.printf("'%S' %n", "sourcecodeexamples");
        System.out.printf("'%15s' %n", "sourcecodeexamples");
        System.out.printf("'%-10s' %n", "sourcecodeexamples");
    }

    private static void printfChar() {
        System.out.printf("%c%n", 's');
        System.out.printf("%C%n", 's');
    }

    private static void printfNumber() {
        System.out.printf("simple integer: %d%n", 10000L);

        System.out.printf(Locale.US, "%,d %n", 10000);
        System.out.printf(Locale.ITALY, "%,d %n", 10000);

        System.out.printf("%f%n", 5.1473);
        System.out.printf("'%5.2f'%n", 5.1473);
        System.out.printf("'%5.2e'%n", 5.1473);
    }

    private static void printfBoolean() {
        System.out.printf("%b%n", null);
        System.out.printf("%B%n", false);
        System.out.printf("%B%n", 5.3);
        System.out.printf("%b%n", "random text");
    }

    private static void printfDateTime() {
        Date date = new Date();
        System.out.printf("%tT%n", date);
        System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
        System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);

        System.out.printf("%1$tA %1$tB %1$tY %n", date);
        System.out.printf("%1$td.%1$tm.%1$ty %n", date);
    }
}

Output


sourcecodeexamples
line
terminators
S
'sourcecodeexamples' 
'SOURCECODEEXAMPLES' 
'sourcecodeexamples' 
'sourcecodeexamples' 
simple integer: 10000
10,000 
10.000 
5.147300
' 5.15'
'5.15e+00'
14:22:53
hours 14: minutes 22: seconds 53
14:22:53 pm 391 391000000 +0000 
Friday February 2021 
19.02.21 
false
FALSE
TRUE
true

References




Comments