What is the difference between System.out.printf and System.out.format?

I read this Stack Overflow page but still don’t understand. If they behave the same way, why does Java have two methods instead of just one? I started wondering about it after reading this article on streams (I try to get the hang of them at this moment). At one point, the author uses printf()

Stream.of("d2", "a2", "b1", "b3", "c")
    .sorted((s1, s2) -> {
        System.out.printf("sort: %s; %s\n", s1, s2);
        return s1.compareTo(s2);
    })
    .filter(s -> {
        System.out.println("filter: " + s);
        return s.startsWith("a");
    })
    .map(s -> {
        System.out.println("map: " + s);
        return s.toUpperCase();
    })
    .forEach(s -> System.out.println("forEach: " + s));

at another format().

Map<Integer, List<Person>> personsByAge = persons
    .stream()
    .collect(Collectors.groupingBy(p -> p.age));

personsByAge
    .forEach((age, p) -> System.out.format("age %s: %s\n", age, p));

There must be some rationale behind it, mustn’t it?

The difference between them is that printf() prints the formatted String into console much like System.out.println() but the format() method returns a formatted string, which you can store or use the way you want.

1 Like

Both return PrintStreams, according to the documentation