Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operator precedence 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 "operator precedence" Watch "operator precedence" New topic

operator precedence

mohammad shaid
Ranch Hand

Joined: May 05, 2010
Posts: 86
Source K&B 5 page 784 .the question on K&B is regarding static import.. i understand the concept of static import but during the coarse of study through that question i rectified the code to see what will the output be.
The code below is similar to the one in K&B,excpet that i have not put the code in 2 different files instead tried it this way.
The whole concept is that i am getting 30 as the output whereas i expected it to be 36. so can someone explain me the logic of operator involvement here??

Is the value 5 substituted before the operation or is it that the n after * gets its value after the operation inside () brackets is over???

Thanks & Regards,
mohammad shaid
Ranch Hand

Joined: May 05, 2010
Posts: 86
As far i know the operation is carried from left to right
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

(n++)*n first becomes (5)*n and then n's value is incremented so the expression becomes 5*6. Look on the internet for post increment operator related tutorials to get more details...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rufat Piriyev
Ranch Hand

Joined: Mar 15, 2010
Posts: 31
In K&B this topic isn't very good described . If you have JLS or Mughal SCJP you must check operator precedence. It says that unary operator doing first
this is from Mughal book:

Postfix operators [] . (parameters) expression++ expression--
Unary prefix operators ++expression --expression +expression -expression ~ !
Unary prefix creation and cast new (type)
Multiplicative * / %
Additive + -
Shift << >> >>>
Relational < <= > >= instanceof
Equality == !=
Bitwise/logical AND &
Bitwise/logical XOR ^
Bitwise/logical OR |
Conditional AND &&
Conditional OR ||
Conditional ?:
Assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
mohammad shaid
Ranch Hand

Joined: May 05, 2010
Posts: 86
Thanks Ankit and Rufat.. i get the point now ..
I agree. Here's the link:
subject: operator precedence
It's not a secret anymore!