The JavaTM Tutorial

| 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` 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 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 shortcut operator `+=`, like this:

> >     i += 2;

> The two previous lines of code are equivalent.

> The following 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`

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

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