Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |

You use the basic assignment operator,`=`

, to assign one value to another. The`MaxVariablesDemo`

program uses`=`

to initialize all its local variables: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 that you wanted to add a number to a variable and assign the result back into the variable, like this://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;You can shorten this statement using the shortcut operatori = i + 2;`+=`

, like this:The two previous lines of code are equivalent.i += 2;The following table lists the shortcut assignment operators and their lengthy equivalents.

Shortcut Assignment OperatorsOperator 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`

Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |

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