aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confused in precedence and associativity rules Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confused in precedence and associativity rules" Watch "Confused in precedence and associativity rules" New topic
Author

Confused in precedence and associativity rules

Adil El mouden
Ranch Hand

Joined: Jun 01, 2005
Posts: 82
Hi,

What is the value of evaluating the following expression (- -1-3 * 10 / 5-1)?

Select the one correct answer.
a)–8
b)–6
c) 7
d) 8
e) 10
f) None of the above.


Answer given is: b

Please i need more explanation on how this expression is evaluated according to precedence and associativity rules.

Thank you.
[ August 10, 2005: Message edited by: Adil El mouden ]

SCWCD 1.4(Loading...), SCJP 1.4(98%), Bachelor of Engineering (computer science)
Sergei Iakhnin
Ranch Hand

Joined: Nov 09, 2004
Posts: 53
That doesn't seem right. The answer should be b) -6
The best way to evaluate any mathematical expression is to try to bracket it properly

(- -1-3 * 10 / 5-1) = ((-(-1) - ((3 * 10) / 5)) - 1)

The expression on the rhs can now be evaluated by rules of arithmetic to give -6


SCJP 1.4, SCWCD 1.4
Adil El mouden
Ranch Hand

Joined: Jun 01, 2005
Posts: 82
ooh! the answer given is : b sorry
I need more explanation.
Thank you.
[ August 10, 2005: Message edited by: Adil El mouden ]
Sherry Jacob
Ranch Hand

Joined: Jun 29, 2005
Posts: 128
This code compiles as :
(-(-1)-((3*10)/5)-1)

= (1-30/5-1)
= 1-6-1
= -6

Which is the correct answer and not 7.


<strong><br />Cheers !!<br /> <br />Sherry<br /></strong><br />[SCJP 1.4]
Pavel Kubal
Ranch Hand

Joined: Mar 13, 2004
Posts: 356
I would like to point out, that multiplication and division has higher precedence than addition and substraction

(--1) gives 0

-(3*10/5) gives -5

-5 -1 gives result -6

;-)
Sergei Iakhnin
Ranch Hand

Joined: Nov 09, 2004
Posts: 53
I would like to point out that

a) --1 is not a legal expression in java
b) - -1 gives 1
c) -(3*10/5) gives -6 in most cases
AnuragSudha Jain
Greenhorn

Joined: Aug 10, 2005
Posts: 6
The Result is simple BODMAS rule

B- Bracket
O - of
D- division
M - Multipilcation
A- addition
S- Subtraction

The Expression is (- -1-3 * 10 / 5-1)

it is divided as
- of -1 -3 * 10 /5 -1
that becomes

+1 -30/5 -1

that becomes

+1 -6-1
That becomes -6

Hope this puts some more light on the ongoing discussion,

Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused in precedence and associativity rules