3.5. Operators
Operators are used to combine values. As you will see in the following sections, Java has a rich set of arithmetic and logical operators and mathematical functions.
3.5.1. Arithmetic Operators
The usual arithmetic operators +, -, *, and / are used in Java for addition, subtraction, multiplication, and division.
The / operator denotes integer division if both operands are integers, and floating-point division otherwise. Integer division by 0 raises an exception, whereas floating-point division by 0 yields an infinite or NaN result.
Integer remainder (sometimes called modulus) is denoted by %. For example, 15 / 2 is 7, 15 % 2 is 1, and 15.0 / 2 is 7.5.
3.5.2. Mathematical Functions and Constants
The Math class contains an assortment of mathematical functions that you may occasionally need, depending on the kind of programming that you do.
To take the square root of a number, use the sqrt method:
double x = 4; double y = Math.sqrt(x); IO.println(y); // prints 2.0
The Java programming language has no operator for raising a quantity to a power: You must use the pow method in the Math class. The statement
double y = Math.pow(x, a);
sets y to be x raised to the power a (xa). The pow method’s arguments are both of type double, and it returns a double as well.
The Math class supplies the usual trigonometric functions:
Math.sin Math.cos Math.tan Math.atan Math.atan2
and the exponential function with its inverse, the natural logarithm, as well as the decimal logarithm:
Math.exp Math.log Math.log10
Java 21 adds a method Math.clamp that forces a number to fit within given bounds. For example:
Math.clamp(-1, 0, 10) // too small, yields lower bound 0 Math.clamp(11, 0, 10) // too large, yields upper bound 10 Math.clamp(3, 0, 10) // within bounds, yields value 3
Finally, three constants denote the closest possible approximations to the mathematical constants π, τ = 2π, and e:
Math.PI Math.TAU Math.E
3.5.3. Conversions between Numeric Types
It is often necessary to convert from one numeric type to another. Figure 3.1 shows the legal conversions.
Figure 3.1: Legal conversions between numeric types
The six solid arrows in Figure 3.1 denote conversions without information loss. The three dotted arrows denote conversions that may lose precision. For example, a large integer such as 123456789 has more digits than the float type can represent. When the integer is converted to a float, the resulting value has the correct magnitude but loses some precision.
int n = 123456789; float f = n; // f is 1.23456792E8
When two values are combined with a binary operator (such as n + f where n is an integer and f is a floating-point value), both operands are converted to a common type before the operation is carried out.
If either of the operands is of type double, the other one will be converted to a double.
Otherwise, if either of the operands is of type float, the other one will be converted to a float.
Otherwise, if either of the operands is of type long, the other one will be converted to a long.
Otherwise, both operands will be converted to an int.
3.5.4. Casts
In the preceding section, you saw that int values are automatically converted to double values when necessary. On the other hand, there are obviously times when you want to consider a double as an integer. Numeric conversions are possible in Java, but of course information may be lost. Conversions in which loss of information is possible are done by means of casts. The syntax for casting is to give the target type in parentheses, followed by the variable name. For example:
double x = 9.997; int nx = (int) x;
Now, the variable nx has the value 9 because casting a floating-point value to an integer discards the fractional part.
If you want to round a floating-point number to the nearest integer (which in most cases is a more useful operation), use the Math.round method:
double x = 9.997; int nx = (int) Math.round(x);
Now the variable nx has the value 10. You still need to use the cast (int) when you call round. The reason is that the return value of the round method is a long, and a long can only be assigned to an int with an explicit cast because there is the possibility of information loss.
3.5.5. Assignment
There is a convenient shortcut for using binary operators in an assignment. For example, the compound assignment operator
x += 4;
is equivalent to
x = x + 4;
(In general, place the operator to the left of the = sign, such as *= or %=.)
Note that in Java, an assignment is an expression. That is, it has a value—namely, the value that is being assigned. You can use that value—for example, to assign it to another variable. Consider these statements:
int x = 1; int y = x += 4;
The value of x += 4 is 5, since that’s the value that is being assigned to x. Next, that value is assigned to y.
Many programmers find such nested assignments confusing and prefer to write them more clearly, like this:
int x = 1; x += 4; int y = x;
3.5.6. Increment and Decrement Operators
Programmers, of course, know that one of the most common operations with a numeric variable is to add or subtract 1. Java, following in the footsteps of C and C++, has both increment and decrement operators: n++ adds 1 to the current value of the variable n, and n-- subtracts 1 from it. For example, the code
int n = 12; n++;
changes n to 13. Since these operators change the value of a variable, they cannot be applied to numbers themselves. For example, 4++ is not a legal statement.
There are two forms of these operators; you’ve just seen the postfix form of the operator that is placed after the operand. There is also a prefix form, ++n. Both change the value of the variable by 1. The difference between the two appears only when they are used inside expressions. The prefix form does the addition first; the postfix form evaluates to the old value of the variable.
int m = 7; int n = 7; int a = 2 * ++m; // now a is 16, m is 8 int b = 2 * n++; // now b is 14, n is 8
Many programmers find this behavior confusing. In Java, using ++ inside expressions is uncommon.
3.5.7. Relational and boolean Operators
Java has the full complement of relational operators. To test for equality, use a double equal sign, ==. For example, the value of
3 == 7
is false.
Use a != for inequality. For example, the value of
3 != 7
is true.
Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal) operators.
Java, following C++, uses && for the logical “and” operator and || for the logical “or” operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The && and || operators are evaluated in “short-circuit” fashion: The second operand is not evaluated if the first operand already determines the value. If you combine two expressions with the && operator,
expression1 && expression2
and the truth value of the first expression has been determined to be false, then it is impossible for the result to be true. Thus, the value for the second expression is not calculated. This behavior can be exploited to avoid errors. For example, in the expression
x != 0 && 1 / x > x + y // no division by 0
the second operand is never evaluated if x equals zero. Thus, 1 / x is not computed if x is zero, and no divide-by-zero error can occur.
Similarly, the value of expression1 || expression2 is automatically true if the first expression is true, without evaluating the second expression.
3.5.8. The Conditional Operator
Java provides the conditional ?: operator that selects a value, depending on a Boolean expression. The expression
condition ? expression1 : expression2
evaluates to the first expression if the condition is true, and to the second expression otherwise. For example,
x < y ? x : y
gives the smaller of x and y.
3.5.9. Switch Expressions
If you need to choose among more than two values, then you can use a switch expression, which was introduced in Java 14. It looks like this:
String seasonName = switch (seasonCode) {
case 0 -> "Spring";
case 1 -> "Summer";
case 2 -> "Fall";
case 3 -> "Winter";
default -> "???";
};
The expression following the switch keyword is called the selector expression, and its value is the selector. For now, we only consider selectors and case labels that are numbers, strings, or constants of an enumerated type. In Chapter 5, you will see how to use switch expressions with other types for pattern matching.
A case label must be a compile-time constant whose type matches the selector type. You can provide multiple labels for each case, separated by commas:
int numLetters = switch (seasonName) {
case "Spring", "Summer", "Winter" -> 6;
case "Fall" -> 4;
default -> -1;
};
When you use the switch expression with enumerated constants, you need not supply the name of the enumeration in each label—it is deduced from the switch value. For example:
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
. . .
Size itemSize = . . .;
String label = switch (itemSize) {
case SMALL -> "S"; // no need to use Size.SMALL
case MEDIUM -> "M";
case LARGE -> "L";
case EXTRA_LARGE -> "XL";
};
In the example, it was legal to omit the default since there was a case for each possible value.
3.5.10. Bitwise Operators
For any of the integer types, you have operators that can work directly with the bits that make up the integers. This means that you can use masking techniques to get at individual bits in a number. The bitwise operators are
& ("and") | ("or") ^ ("xor") ~ ("not")
These operators work on bit patterns. For example, if n is an integer variable, then
int fourthBitFromRight = (n & 0b1000) / 0b1000;
gives you a 1 if the fourth bit from the right in the binary representation of n is 1, and 0 otherwise. Using & with the appropriate power of 2 lets you mask out all but a single bit.
There are also >> and << operators which shift a bit pattern right or left. These operators are convenient when you need to build up bit patterns to do bit masking:
int fourthBitFromRight = (n & (1 << 3)) >> 3;
Finally, a >>> operator fills the top bits with zero, unlike >> which extends the sign bit into the top bits. There is no <<< operator.
3.5.11. Parentheses and Operator Hierarchy
Table 3.4 shows the precedence of operators. If no parentheses are used, operations are performed in the hierarchical order indicated. Operators on the same level are processed from left to right, except for those that are right-associative, as indicated in the table. For example, && has a higher precedence than ||, so the expression
a && b || c
means
(a && b) || c
Since += associates right to left, the expression
a += b += c
means
a += (b += c)
That is, the value of b += c (which is the value of b after the addition) is added to a.
Table 3.4: Operator Precedence
Operators |
Associativity |
[] . () (method call) |
Left to right |
! ~ ++ -- + (unary) - (unary) () (cast) new |
Right to left |
* / % |
Left to right |
+ - |
Left to right |
<< >> >>> |
Left to right |
< <= > >= instanceof |
Left to right |
== != |
Left to right |
& |
Left to right |
^ |
Left to right |
| |
Left to right |
&& |
Left to right |
|| |
Left to right |
?: |
Right to left |
= += -= *= /= %= &= |= ^= <<= >>= >>>= |
Right to left |
