Page 108 - Introduction to Programming with Java: A Problem Solving Approach
P. 108
74 Chapter 3 Java Basics
worry about it; it’s just a conversion factor that some scientist came up with.” If someone who is unfamiliar with the Fahrenheit scale reads the above statement, they won’t know the significance of the 32.0. Using a FREEZING_POINT named constant makes things clearer.
3.15 Arithmetic Operators
We’ve talked about numbers for a while now—how to declare numeric variables, how to assign numbers, and how to work with numeric constants. In addition, we’ve shown a few examples of using numbers in mathematical expressions. In this section and the next two sections, we study expressions in more depth. An expression is a combination of operands and operators that performs a calculation. Operands are variables and constants. An operator is a symbol, like + or -, that performs an operation. In this section, we’ll look at arithmetic operators for numeric data types. Later, we’ll look at operators for other data types.
Addition, Subtraction, and Multiplication
Java’s +, -, and * arithmetic operators should be familiar to you. They perform addition, subtraction, and multiplication, respectively.
Floating-Point Division
Java performs division differently depending on whether the numbers/operands being divided are integers or whether they’re floating-point numbers. Let’s first discuss floating-point division.
When the Java Virtual Machine (JVM) performs division on floating-point numbers, it performs “calcu-
Apago PDF Enhancer
lator division.” We call it “calculator division” because Java’s floating-point division works the same as divi- sion performed by a standard calculator. For example, if you enter this on your calculator, what is the result?
7.0÷2.0=
The result is 3.5. Likewise, this line of Java code prints 3.5:
System.out.println(7.0 / 2.0);
Note that calculators use the ÷ key for division and Java uses the / character.
To explain arithmetic operators, we’ll need to evaluate lots of expressions. To simplify that discussion,
we’ll use the ⇒ symbol. It means “evaluates to.” Thus, this next line says that 7.0 / 2.0 evaluates to 3.5: 7.0 / 2.0 ⇒ 3.5
This next line asks you to determine what 5 / 4. evaluates to: 5 / 4. ⇒ ?
5 is an int and 4. is a double. This is an example of a mixed expression. A mixed expression is an expres- sion that contains operands with different data types. double values are considered to be more complex than int values because double values contain a fractional component. Whenever there’s a mixed expres- sion, the JVM temporarily promotes the less complex operand’s type so that it matches the more complex operand’s type, and then the JVM applies the operator. In the 5 / 4. expression, the JVM promotes 5 to a