Java provides special operators that can be used to combine an arithmetic operation
with an assignment. As you probably know, statements like the following are quite
common in programming:
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
This version uses the += assignment operator. Both statements perform the same
action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a/2 and puts that result back into a.
There are assignment operators for all of the arithmetic, binary operators. Thus,
any statement of the form
var = var op expression;
can be rewritten as
var op= expression;
The assignment operators provide two benefits. First, they save you a bit of typing,
because they are “shorthand” for their equivalent long forms. Second, they are
implemented more efficiently by the Java run-time system than are their equivalent
long forms. For these reasons, you will often see the assignment operators used in
professionally written Java programs.
Here is a sample program that shows several op= operator assignments in action:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a = 6
b = 8
c = 3
No comments:
Post a Comment