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

Trail: Learning the Java Language
Lesson: Language Basics

Assignment Operators

You use the basic assignment operator, =, to assign one value to another. The MaxVariablesDemo (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;
The Java programming language also provides several shortcut assignment operators that allow you to perform an arithmetic, shift, or bitwise operation and an assignment operation all with one operator. Suppose you want to add a number to a variable and assign the result back into the variable, as follows.
i = i + 2;
You can shorten this statement using the shortcut operator +=.
i += 2;
The previous two lines of code are equivalent.

The following table lists the shortcut assignment operators and their lengthy equivalents.

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


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

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.