Asad Moosvi Asad Moosvi - 25 days ago 7
Java Question

How does the new operator create a new object?

I've just started learning Java and I'm a bit confused about the syntax used for creating new objects.

Take the following:

SomeClass someObject = new SomeClass(1, 2, 3);


What exactly is the syntax that comes after
new
? Is that the constructor call itself or is it just the class name with some arguments? Does
new
look at that and know what constructor to call based on those arguments or is the
SomeClass(1, 2, 3)
the constructor call itself?

I would like to know what steps are followed when
someObject
is created and what
new
's role is.

What I don't understand is... is
SomeClass(1, 2, 3)
after
new
the actual constructor call on that same line? Or is it called later by
new
?

Update:

The source of my confusion has probably been the terminology used behind
new
. As it turns out,
new
is not an operator at all.
new
is actually a keyword. That makes much more sense to me now.

This answers my question: Why is new called an operator in Java?

Answer Source

new, the specified Type (SomeClass), the brackets () and possibly arguments etc. are part of one expression, according to the JLS "Class Instance Creation Expressions".

So it does not make sense to separate new and the parts of the expression.

(But the arguments to the constructor are evaluated after memory allocation but before the call to the constructor.)