Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 151

Compound Assignment Operators

Оглавление

Besides the simple assignment operator (=), Java supports numerous compound assignment operators. For the exam, you should be familiar with the compound operators in Table 2.6.

TABLE 2.6 Compound assignment operators

Operator Example Description
Addition assignment a += 5 Adds the value on the right to the variable on the left and assigns the sum to the variable
Subtraction assignment b -= 0.2 Subtracts the value on the right from the variable on the left and assigns the difference to the variable
Multiplication assignment c *= 100 Multiplies the value on the right with the variable on the left and assigns the product to the variable
Division assignment d /= 4 Divides the variable on the left by the value on the right and assigns the quotient to the variable

Compound operators are really just glorified forms of the simple assignment operator, with a built-in arithmetic or logical operation that applies the left and right sides of the statement and stores the resulting value in the variable on the left side of the statement. For example, the following two statements after the declaration of camel and giraffe are equivalent when run independently:

int camel = 2, giraffe = 3; camel = camel * giraffe; // Simple assignment operator camel *= giraffe; // Compound assignment operator

The left side of the compound operator can be applied only to a variable that is already defined and cannot be used to declare a new variable. In this example, if camel were not already defined, the expression camel *= giraffe would not compile.

Compound operators are useful for more than just shorthand—they can also save you from having to explicitly cast a value. For example, consider the following. Can you figure out why the last line does not compile?

long goat = 10; int sheep = 5; sheep = sheep * goat; // DOES NOT COMPILE

From the previous section, you should be able to spot the problem in the last line. We are trying to assign a long value to an int variable. This last line could be fixed with an explicit cast to (int), but there's a better way using the compound assignment operator:

long goat = 10; int sheep = 5; sheep *= goat;

The compound operator will first cast sheep to a long, apply the multiplication of two long values, and then cast the result to an int. Unlike the previous example, in which the compiler reported an error, the compiler will automatically cast the resulting value to the data type of the value on the left side of the compound operator.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх