Expression Evaluation Order


The order of evaluation in a complex expression is important. The basic rules:

  • Java evaluates parenthesized expressions first, from innermost parentheses to outermost parentheses.

  • Certain operators have higher precedence than others; for example, multiplication has a higher precedence than addition.

  • Otherwise, expressions are evaluated from left to right.

You should use parentheses in particularly complex expressions, since the precedence rules can be difficult to remember. In fact, some of them are counterintuitive. Parenthesizing is worth the effort to ensure that there is no misunderstanding about how an expression will be evaluated. Just don't go overboard with the parenthesesmost developers should be familiar with the basic precedence rules.

Use parentheses to simplify understanding of complex expressions.


Here are a few examples of how precedence affects the result of an expression:

 assertEquals(7, 3 * 4 - 5);     // left to right assertEquals(-11, 4 - 5 * 3);   // multiplication before subtraction assertEquals(-3, 3 * (4 - 5));  // parentheses evaluate first 

When in doubt, write a test!



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net