26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

78 Introduction <strong>to</strong> <strong>Java</strong> Applications Chapter 2<br />

Opera<strong>to</strong>r(s) Operation(s) Order of evaluation (precedence)<br />

() Parentheses Evaluated first. If the parentheses are nested, the<br />

expression in the innermost pair is evaluated first. If<br />

there are several pairs of parentheses on the same<br />

level (i.e., not nested), they are evaluated left <strong>to</strong> right.<br />

*, / and % Multiplication<br />

Division<br />

Modulus<br />

+ or - Addition<br />

Subtraction<br />

Fig. Fig. 2.17 2.17 Precedence of arithmetic opera<strong>to</strong>rs.<br />

Now, let us consider several expressions in light of the rules of opera<strong>to</strong>r precedence.<br />

Each example lists an algebraic expression and its <strong>Java</strong> equivalent.<br />

The following is an example of an arithmetic mean (average) of five terms:<br />

Algebra:<br />

<strong>Java</strong>: m = ( a + b + c + d + e ) / 5;<br />

The parentheses are required, because division has higher precedence than that of addition.<br />

The entire quantity ( a+b+c+d+e) is <strong>to</strong> be divided by 5. If the parentheses are erroneously<br />

omitted, we obtain a +b+c+d+e/5, which evaluates as<br />

The following is an example of the equation of a straight line:<br />

Algebra:<br />

<strong>Java</strong>: y = m * x + b;<br />

No parentheses are required. The multiplication opera<strong>to</strong>r is applied first, because multiplication<br />

has a higher precedence than that of addition. The assignment occurs last, because it<br />

has a lower precedence than that of multiplication and division.<br />

The following example contains modulus (%), multiplication, division, addition and<br />

subtraction operations:<br />

Algebra:<br />

m<br />

e<br />

a + b + c + d + --<br />

5<br />

a+ b+ c+ d+ e<br />

= ---------------------------------------<br />

5<br />

y = mx+ b<br />

z = pr%q + w/x – y<br />

Evaluated second. If there are several of this type of<br />

opera<strong>to</strong>r, they are evaluated from left <strong>to</strong> right.<br />

Evaluated last. If there are several of this type of opera<strong>to</strong>r,<br />

they are evaluated from left <strong>to</strong> right.<br />

<strong>Java</strong>: z = p * r % q + w / x - y;<br />

6<br />

1 2 4 3 5<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!