Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Oerator precedence

 
Vishnu Munnangi
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
* 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
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply,

I was of the opinion that they * precedes %.
Thanks for Clarification.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic