The following code when compile is OK, but from the point of operator precedence view, it seems it should not be OK, because operator new has lower precedence than operator . : new MyClass().myMethod(); Thanks in advance.
Hi ... I am not sure on what I write below! I want some experts to clarify on this. Anyways, thought of providing another pointer to look at this question.
See ... Syntax wise the compiler PASSes this statement as the instance method "myMethod()" is invoked on an object instance.
Now when executing this statement, HOW DO YOU PEOPLE SAY THAT 'new' IS EXECUTED FIRST !!! See the way I interpret!
First "." operator gets executed as it has higher precedence than 'new'. Now JVM looks and comes to know that myMethod() is called, but it is confused on which instance it is called. So it then executes, the 'new' statement and then calls the method on that instance.
If the interpretation is like what I have written just above, then the code behaves as per JLS, without bypassing the precedence rules. Right?
Again, I am not sure on this. Is there any way to confirm on this???
I think the compiler treats "new myClass().myMethod;" as "new( myClass() ).myMethod();".
Compilers encounter tokens from left to right and, on encountering the new operator, expect to see an identifier followed by a left paren, possibly a parameter list, and a right paren (I omit several other cases here). This does not follow the precedence rules, but see the following quote from the Java Language Specification:
15.7.5 Evaluation Order for Other Expressions The order of evaluation for some expressions is not completely covered by these general rules, because these expressions may raise exceptional conditions at times that must be specified. See, specifically, the detailed explanations of evaluation order for the following kinds of expressions:
The final authority on Java syntax as implemented by Java compilers is not the precedence table but the context-free grammars in the Java Language Specification which are, in turn, the input to the JavaCC parser generator and similar programs. You could go through chapter 15 and verify the parsing of "new MyClass().myMethod();".
SCJP 1.4, SCWCD in process
Joined: Oct 29, 2004
Thanks for your reply. I understand better now. new MyClass() is translated to a call to the constructor at compile time. At runtime the constructor run first to create an instance of the MyClass, then the instance method MyMethod() is called.