Operators perform some function on either one or two operands.
Table 3.2. Arithmetic Operators
| Operator | Use | Description |
|---|---|---|
| + | op1 + op2 | Adds op1 and op2 |
| - | op1 - op2 | Subtracts op2 from op1 |
| * | op1 * op2 | Multiplies op1 and op2 |
| / | op1 / op2 | Divides op1 by op2 |
| % | op1 % op2 | Computes the remainder of dividing op1 by op2 |
| + | + op | Indicates a positive value |
| - | - op | Arithmetically negates op |
| ++ | op ++ | Increments op by 1; Eval before incrementing |
| ++ | ++ op | Increments op by 1; Eval after incrementing |
| -- | op -- | Decrements op by 1; Eval before decrementing |
| -- | -- op | Decrements op by 1; Eval after decrementing |
![]() | Caution |
|---|---|
![]() The Java language extends the definition of the operator + to include string concatenation. |
Table 3.3. Relational Operators
| Operator | Use | Returns true if |
|---|---|---|
| > | op1 > op2 | op1 is greater than op2 |
| >= | op1 >= op2 | op1 is greater than or equal to op2 |
| < | op1 < op2 | op1 is less than to op2 |
| <= | op1 <= op2 | op1 is less than or equal to op2 |
| == | op1 == op2 | op1 and op2 are equal |
| != | op1 != op2 | op1 and op2 are not equal |
Table 3.4. Conditional Operators
| Operator | Use | Returns true if |
|---|---|---|
| && | op1 && op2 | op1 and op2 are both true |
| || | op1 || op2 | op1 or op2 is true |
| ! | ! op | op is false |
Table 3.5. Bitwise Operators
| Operator | Use | Operation |
|---|---|---|
| >> | op1 >> op2 | shift bits of op1 right by distance op2 |
| << | op1 << op2 | shift bits of op1 left by distance op2 |
| >>> | op1 >>> op2 | shift bits of op1 right by distance op2 (unsigned) |
| & | op1 & op2 | bitwise and |
| | | op1 | op2 | bitwise or |
| ^ | op1 ^ op2 | bitwise xor |
| ~ | ~ op | bitwise complement |
You use the assignment operator, =, to assign one value to another.
![]() | Caution |
|---|---|
![]() The assignment operator just changes the pointer of Reference variables. |
The code:
StringBuffer car1 = new StringBuffer("Toyota");
StringBuffer car2 = new StringBuffer("Ford");Results in the following memory structures:
If the Assignment operator is used:
car2 = car1;
The car2 variable is pointed to the same object as car1 variable:
A common source of mistakes is to think that car2 holds a copy of the object in car1 and to change it not expecting this to affect the object held by car1.
Table 3.6. Short Cut for the Assignment Operator
| 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 |
Copyright © 1998-2009 Dilvan Moreira