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 fromjava.lang
.out
is a static field inSystem
, and it’s a reference to aPrintStream
object.- So
System.out
is an instance ofPrintStream
.
✅ What is println
?
println
is an instance method ofPrintStream
.- 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.