Java.Java8.Explain the System.out::println expression.

The expression System.out::println is a method reference, and specifically it’s:

🔹 Type: Reference to an instance method of a particular object (Type #2)

Let’s break it down:


✅ What is System.out?

  • System is a class from java.lang.
  • out is a static field in System, and it’s a reference to a PrintStream object.
  • So System.out is an instance of PrintStream.

✅ What is println?

  • println is an instance method of PrintStream.
  • It has several overloaded versions: println(String), println(int), etc.

✅ So what does System.out::println mean?

It is a method reference to the println method of the System.out object.

This is equivalent to writing a lambda like:

x -> System.out.println(x)

So if you use it like this:

List<String> names = List.of("Stanley", "Anna", "Bob");
names.forEach(System.out::println);

It means: “for each element in names, call System.out.println(element).”

✅ Why is it useful?

  • It’s more concise than a lambda.
  • It’s very readable for common operations like logging or printing.
This entry was posted in Без рубрики. Bookmark the permalink.