Working with Numbers and Expressions
In Book II, Chapter 2, you discover the various primitive numeric types that are supported by Java. In this chapter, you build on that knowledge by doing basic operations with numbers. Much of this chapter focuses on the complex topic of expressions, which combine numbers with operators to perform calculations. But this chapter also covers techniques for formatting numbers when you display them and performing advanced calculations using the Math class. In addition, you find out why Java's math operations sometimes produce results you might not expect.
Working with Arithmetic Operators
An operator is a special symbol or keyword that's used to designate a mathematical operation or some other type of operation that can be performed on one or more values, called operands. In all, Java has about 40 different operators. This chapter focuses on the operators that do arithmetic. These arithmetic operators perform basic arithmetic operations, such as addition, subtraction, multiplication, and division. In all, there are 7 of them. Table 3-1 summarizes them.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder |
++ | Increment |
– | Decrement |
The following section of code can help clarify how these operators work for int types:
int a = 21, b = 6;
int c = a + b; // c is 27
int d = a - b; // d is 15
int e = a * b; // e is 126
int f = a / b; // f is 3 (21 / 6 is 3 remainder 3)
int g = a % b; // g is 3 (20 / 6 is 3 remainder 3)
a++; // a is now 22
b--; // b is now 5
Notice that for division, the result is truncated. Thus 21/6 returns 3, not 3.5. For more information about integer division, see the section "Dividing Integers" later in this chapter.
Here's how the operators work for double values:
double x = 5.5, y = 2.0;
double m = x + y; // m is 7.5
double n = x - y; // n is 3.5
double o = x * y; // o is 11.0
double p = x / y; // p is 2.75
double q = x % y; // q is 1.5
x++; // x is now 6.5
y--; // y is now 1.0
Warning | When you divide two int values, the result is an integer value, even if you assign it to a double variable. For example: int a = 21, b = 6; |
If that's not what you want, you can cast one of the operands to a double before performing the division, like this:
int a = 21, b = 6;
double answer = (double)a / b; // answer = 3.5
The moral of the story is that if you want to divide int values and get an accurate double result, you must cast at least one of the int values to a double.
Tip | Here are a few additional things to think about tonight as you lay awake pondering the wonder of Java's arithmetic operators:
|
No comments:
Post a Comment