Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Strange code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strange code" Watch "Strange code" New topic

Strange code

Nick Petas
Ranch Hand

Joined: Jan 31, 2007
Posts: 40
I stumbled uppon this code :

Is it valid code and what exactly does it do?
Thank you.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

What exactly do you find strange about it?

You can write it on one line:

It does the same as this:

As you know, you use the "." syntax to call a method on an object: variable name, dot, method name, parentheses, semi-colon. If the method returns something, you can assign the return value to a variable. Then on that variable you can again call a method.

You can also do this in one go. So, for example the expression new ClassName(this) gives you a ClassName object; you don't need to assign that to a variable first, you can directly call a method on it by putting a "." and the method name after it: new ClassName(this).setMethod1();. And the method call in turn can return an object, on which you can again call a method directly. So you can chain multiple method calls like that.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Nick Petas
Ranch Hand

Joined: Jan 31, 2007
Posts: 40
Oh yes of course.
Now I get it.
Thanks a lot for the rapid answer!
I agree. Here's the link:
subject: Strange code
It's not a secret anymore!