Section 3.8. Operator Precedence

   

3.8 Operator Precedence

There are rules regarding the order of precedence the compiler will follow when executing a mathematical statement with multiple operators. These are generally the standard mathematical rules for operator precedence:

  1. Operators inside parentheses

  2. Multiplication and division (left to right)

  3. Addition and subtraction (left to right)

This short program simply sets two different variables to the value of a mathematical expression result. The expression uses multiple mathematical operators. Each expression uses identical operators and numeric values. One expression shows left to right precedence, while the other shows parenthetical enforcement of precedence.

 /*  File: chp3.opPrecedence.java Purpose: demo operator precedence Author: E Hewitt */ public class opPrecedence {     public static void main(String[] args) {     // this program simply demonstrates left to     // right and parenthetical precedence in mathematical     // operations int x = 6 + 6 * 2 / 6 - 4; System.out.println("x is: " + x); // x is 4 // same thing, but with parentheses int y = (6 + 6) * (2 / (6 - 4)); // y is 12 System.out.println("y is: " + y);     } } 

Note

I am writing out these code snippets as complete working programs to encourage you to type in, compile, and run them. This can help you get used to reading Java, and begin to notice different kinds of errors (such as ';' expected ) and subtle behaviors (such as a mathematical result of 0 that might slip through the cracks if you're not careful about types).



   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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