The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Learning the Java Language
Lesson: The Nuts and Bolts of the Java Language

Assignment Operators

You use the basic assignment operator, =, to assign one value to another. The MaxVariables(in a .java source file) program uses = to initialize all of its local variables:
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;

// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;

// other primitive types
char aChar = 'S';
boolean aBoolean = true;
Java also provides several short cut assignment operators that allow you to perform an arithmetic, logical, or bitwise operation and an assignment operation all with one operator. Suppose you wanted to add a number to a variable and assign the result back into the variable, like this:
i = i + 2;
You can shorten this statement using the short cut operator +=.
i += 2;
The two previous lines of code are equivalent.

This table lists the shortcut assignment operators and their lengthy equivalents:

Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
&= op1 &= op2 op1 = op1 & op2
|= op1 |= op2 op1 = op1 | op2
^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2
>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search