aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Oerator 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 "Oerator precedence" Watch "Oerator precedence" New topic
Author

Oerator precedence

Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Hi everyone,

This is one of the Questions from Dan's mock exam.
Please go through the code..

class EBH002 {
static int m(int i) {System.out.print(i + ", "); return i;}
public static void main(String s[]) {
m(m(1) + m(2) % m(3) * m(4));
}}

What is the result of attempting to compile and run the program?

a. Prints: 1, 2, 3, 4, 0,
b. Prints: 1, 2, 3, 4, 3,
c. Prints: 1, 2, 3, 4, 9,
d. Prints: 1, 2, 3, 4, 12,
e. Prints: 2, 3, 4, 1, 9,
f. Prints: 2, 3, 4, 1, 3,
g. Run-time error
h. Compile-time error
i. None of the above

The answer given is C.
My doubt here is Multiplication(*), precedes Percentage(%) operator.
so the expression
m(m(1) + m(2) % m(3) * m(4));
is evaluated as
--> m(1 + (2 % (3 * 4)))
--> m(1 + (2 % (12)))
--> m(1 + 2)
which is equal to m(3).
So the answer i believe is b
Please Correct me if I am wrong.
Thanks in advance.
Louie van Bommel
Ranch Hand

Joined: Aug 17, 2004
Posts: 76
* and % have same precedence, and therefore if
x = a % b * c they get evaluated left to right.

jls:

15.17 Multiplicative Operators
The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).
Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Thanks for the reply,

I was of the opinion that they * precedes %.
Thanks for Clarification.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Oerator precedence