Java Reference
In-Depth Information
2.11 Evaluating Expressions and Operator Precedence
Java expressions are evaluated in the same way as arithmetic expressions.
Key
Point
Writing a numeric expression in Java involves a straightforward translation of an arithmetic
expression using Java operators. For example, the arithmetic expression
-
+
+
3
+
4 x
10( y
5)( a
b
c )
4
x +
9
+
x
y
-
+
9
¢
5
x
can be translated into a Java expression as:
( 3 + 4 * x) / 5 - 10 * (y - 5 ) * (a + b + c) / x +
9 * ( 4 / x + ( 9 + x) / y)
Though Java has its own way to evaluate an expression behind the scene, the result of a Java
expression and its corresponding arithmetic expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java expression. Operators contained within pairs of
parentheses are evaluated first. Parentheses can be nested, in which case the expression in the
inner parentheses is evaluated first. When more than one operator is used in an expression, the
following operator precedence rule is used to determine the order of evaluation.
evaluating an expression
operator precedence rule
Multiplication, division, and remainder operators are applied first. If an expression
contains several multiplication, division, and remainder operators, they are applied
from left to right.
Addition and subtraction operators are applied last. If an expression contains several
addition and subtraction operators, they are applied from left to right.
Here is an example of how an expression is evaluated:
3 + 4 * 4 + 5 * ( 4 + 3 ) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 - 1
(2) multiplication
3 + 16 + 5 * 7 - 1
(3) multiplication
3 + 16 + 35 - 1
(4) addition
19 + 35 - 1
(5) addition
54 - 1
(6) subtraction
53
Listing 2.5 gives a program that converts a Fahrenheit degree to Celsius using the formula
( 9 )( fahrenheit
celsius
=
-
32).
L ISTING 2.5 FahrenheitToCelsius.java
1 import java.util.Scanner;
2
3 public class FahrenheitToCelsius {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 System.out.print( "Enter a degree in Fahrenheit: " );
 
 
Search WWH ::




Custom Search