File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes new class.method() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "new class.method() " Watch "new class.method() " New topic

new class.method()

Kok Lum Chan

Joined: Apr 12, 2009
Posts: 10
Hi all,

The above codes are from K&B SCJP6 (Chapter 2).

I have a difficulty understanding the last line. Usually, we do something like below :

why oWhy = new why();

Why this time it can allocate an object to the heap and calling the method at the same time ?

Any advice is appreciated.
Malte Wannerskog
Ranch Hand

Joined: Jan 06, 2011
Posts: 92

update: fixed

OCPJP (310-065) - 88%
Relja Damnjanovic

Joined: Feb 19, 2010
Posts: 6

Hi koklum!

The thing you're asking is pretty simple - in the case of the written code the author doesn't need the object instance any more so he/she is using the shorter syntax for the call.

So, in your example you create the object and reference it with a variable oWhy

and then invoke the method on that object

In the book example case, the created object is not assigned to variable, but is directly used only to invoke the method.

After this line this object is unreachable so if we would like to use it again we would have to instantiate it again.

Take look at the chapter dealing with Strings and its methods, you should see more examples like this dealing withe the piping the methods one to another, basically it's a same thing - only here first called method is a constructor, and constructors have different syntax for invocation.

SCJP done, SCWCD on the way!
Kok Lum Chan

Joined: Apr 12, 2009
Posts: 10
Hi Relja,

Thank your for your clear explanation. It make sense to me now.

I agree. Here's the link:
subject: new class.method()
It's not a secret anymore!