Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println - Is this method chaining in Java?

I am wondering about the the following piece of Java code:

"System.out.println". I am right about this:

"System" is a static class. ".out" is a method of class "System". This is the bit I am slighty confused about ".println"-- what class / object is this a method of?

Also, is this concept known as "method chaining"?

Thanks

GF

like image 954
Grungefreak Avatar asked Mar 16 '26 23:03

Grungefreak


2 Answers

No, it's not method chaining. You're right about System being a class (just a regular class, not "static" - only inner classes can be static), but out is a static field of the class (of the type java.io.PrintStream), and only println() is a method of PrintStream.

This is an example of method chaining:

String s = "Long String ".toUpperCase().substring(4).trim()
like image 194
Michael Borgwardt Avatar answered Mar 19 '26 13:03

Michael Borgwardt


The class System has a member variable 'out', of type PrintStream. It's not a method.

Class PrintStream has a method println(String).

So no, not method chaining.

Method chaining, as far as I know, is just returning this where you might return void, allowing for multiple invocations of methods in a single statement and perhaps a more natural expression of a DSL. You can see it in action in the StringBuilder's append(String) method

StringBuilder builder = new StringBuilder()
  .append("I am a ")
  .append("String")
  .append("Builder");

If you're interested in knowing more, Martin Fowler talked about Method Chaining here.

like image 33
brabster Avatar answered Mar 19 '26 13:03

brabster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!