Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Operator Precedence

Vineela Devi
Ranch Hand
Posts: 191
Hi Ranchers,
Pls go thru the following code:

Pls explain the o/p of the above code.
i thought the o/p will be 1,2,3,4,3.But its not correct.
Pls expalin in detail.
Regards
Vineela

Gian Franco
blacksmith
Ranch Hand
Posts: 979
Hi Vineela,
1.) every call to the m method is evaluated,
this results in:
m( 1 + 2 % 3 * 4 )
2.) the expression is evaluated from left
to right and following the precendence
rules which looks like this with brackets:
m1(1 + ((2 % 3) * 4))
and results in:
m1(9)
the whole thing gives us: 1,2,3,4,9,
HTH, greetings,
Gian Franco

Vineela Devi
Ranch Hand
Posts: 191
Hi Gian,
But A/c to Operator Precedence '*' is having highest precedence than '%'.So, i think the exp should be evaluated as
1+(2%(3*4)) resulting in a value of 3.
Am i going wrong anywhere?
Pls correct me.
Regards
Vineela

Gian Franco
blacksmith
Ranch Hand
Posts: 979
Hi Vineela,
the operators * and % have the same precedence and
it depends on which one comes first when read from
left to right. So the following:
m(m(1) + m(4) * m(2) % m(3));

gives another result than
m(m(1) + m(2) % m(3) * m(4));

HTH, greetings,
Gian Franco

seema pujari
Greenhorn
Posts: 1
Hi Vineela,
*, / and % have the same precedence. They associate from left to right.

Vineela Devi
Ranch Hand
Posts: 191
Hi Gian,
Thanku.I got it.
Regards
Vineela