This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I would have a question about operator's precedence. Here's an example extracted from Dan's mock exam:
Answer: Prints: 1, 2, 3, 4, 9, I understand the order of four digits 1, 2, 3, 4 which indicates that, as said in a precedent topic in Javaranch about operator, the order of operations has nothing to do with operators precedence, which tells about place of parenthesis. However, I don't understand the last digit, 9. For me, I thought that * had the highest precedence compared to % so m(1) + m(2) % m(3) * m(4) is equivalent for me to m(1) + (m(2) % (m(3) * m(4))) and I would wait 1 + (2%12) = 1 + 2 = 3 as output. Instead, as far as I understand the result, m(1) + m(2) % m(3) * m(4) is equivalent to m(1) + ((m(2) % (m(3)) * m(4)) which gives 1 + (2 *4) =9 as output. Am I wrong in saying that * has higher priority than %, and is it more correct to say that they have the same precedence, and hence, are evaluated left to right, so % before *? I'm sure i'm missing something here, but I don't see what exactly. I would be very grateful for any assistance, Thanks in advance for your help, Cyril.
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
OK. Thanks all for your answers and links. Here the key is that the 3 operators * / % all have the same precedence. This was not well explained in my book Complete Java 2 certification Study Guide. P.32 we can read: Unary: ... Arithmetic * / % + - ... ... Bitwise & ^| So * / % and & ^| are presented exactly in the same form, and I've wrongly deduced from this that * had precedence on / % exactly as & had precedence on ^ and |. Cyril.
Joined: Mar 05, 2003
Here is the scoop on precedence: postfix operators expr++ expr-- unary operators ++expr --expr +expr ~ ! cast (type)expr multiplicative * / % additive + - shift << >> >>> relational < > >= <= instanceof equality == != AND & exclusive OR ^ inclusive OR | conditional AND && conditional OR || conditional ?: assignment = op= I am not sure whether cast has lower precedence than the other unary operators. My two reliable sources (JLS, JPL) seem to disagree. I cannot think of a way to test it. Operator precedence is the "stickiness" of operators relative to each other. Precedence tells you how to add parentheses. [ July 13, 2003: Message edited by: Marlene Miller ]