Java Reference
In-Depth Information
EXAMPLE 2-28
This example shows several compound assignment statements that are equivalent to
simple assignment statements.
Simple Assignment Statement
Compound Assignment Statement
i = i + 5;
i += 5;
counter = counter + 1;
counter += 1;
sum = sum + number;
sum += number;
amount = amount *(interest + 1);
amount *= interest + 1;
x = x / ( y + 5);
x /= y + 5;
Any compound assignment statement can be converted into a simple assignment
statement. However, a simple assignment statement may not be (easily) converted
into a compound assignment statement. Consider the following simple assignment
statement:
x = x * y + z - 5;
To write this statement as a compound assignment statement, the variable x must be a
common factor in the right side, which is not the case. Therefore, you cannot immediately
convert this statement into a compound assignment statement. In fact, the equivalent
compound assignment statement is:
x *= y + (z - 5)/x;
which is more complicated than the simple assignment statement. Furthermore, in the
preceding compound statement, x cannot be zero. We recommend avoiding such com-
pound expressions.
PROGRAMMING EXAMPLE: Convert Length
Write a program that takes as input given lengths expressed in feet and inches. The
program should then convert and output the lengths in centimeters. Assume that the
lengths given in feet and inches are integers.
Input: Length in feet and inches
Output: Equivalent length in centimeters
 
Search WWH ::




Custom Search