• Post Reply Bookmark Topic Watch Topic
  • New Topic

Operator Precedence -- "new" and "."  RSS feed

Rob Chee
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can someone please help me figure-out why the precedence rules don't seem to be followed in this case:

public class Test {
public static void main(String[] args) {
new Test() . go(); //This line
public void go() {}

In "new Test() . go()", I'm following the precedence order as explained in section 9.5 of "The Java Programming Language", 4th ed:

i) Postfix operators: [] . (params) expr++ expr--
ii) Unary operators: ++expr --expr +expr -expr ~ !
iii) new (type)expr

So... breaking down "new Test() . go()", I think about it as follows:
1) () <-- params from Test()... nothing to eval, so continue
2) . <-- member selection operator... would apparently bind to "Test()"
3) () <-- params from go()... nothing to eval, so continue
4) Now that precedence level 1 is complete, moving on to level 2... nothing in level 2. So now move-on to level 3: new {Test()}

By following the precedence rules, I don't see how this makes sense. Below I've grouped things by braces for clarity, with precedence nums immediately following the opening braces. I've kept in mind the left-associativity of the operators in the case where "(params)" and "." are at the same precedence level:
{4new {3{1Test()} . {2go()}}}
... which doesn't make sense.

But the way the compiler seems to handle it is that it seems to give the "new" operator higher precedence than the ".", as if the precedence were really:
i) (params)
ii) new
iii) .

...resulting in:

1) () from Test()
2) () from go()
3) new
4) .
As shown here:
{4{3new {1Test()}} . {2go()}}

Could someone *please* shed some light on this? I'd want to understand the precedence rules.

Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Phewww...you make it complicated )

Hmmm...i try my best... I think the code is executed from left to right because new Test().go() is in the same level. If in the case of new Test().go(new Test().getNewMethod()) than the parameter in go() --> new Test().getNewMethod() will be executed in the first place because it is needed to be used in new Test().go().
Joni Salonen
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The expression "new Test().go()" is a method invocation expression of type "primary . identifier ( )" as you can read from

"Primary" can be any primary expression but in this case it's a "ClassInstanceCreationExpression" of the type "new ClassOrInterfaceType ( )". See

Edit: Note that operator precedence doesn't affect how the program text is parsed
[ October 22, 2006: Message edited by: Joni Salonen ]
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!