2. Operators

Operators perform some function on either one or two operands.

Table 3.2. Arithmetic Operators

OperatorUseDescription
+op1 + op2Adds op1 and op2
-op1 - op2Subtracts op2 from op1
*op1 * op2Multiplies op1 and op2
/op1 / op2Divides op1 by op2
%op1 % op2Computes the remainder of dividing op1 by op2
++ opIndicates a positive value
-- opArithmetically negates op
++op ++Increments op by 1; Eval before incrementing
++++ opIncrements op by 1; Eval after incrementing
--op --Decrements op by 1; Eval before decrementing
---- opDecrements op by 1; Eval after decrementing

[Caution]Caution

The Java language extends the definition of the operator + to include string concatenation.

Table 3.3. Relational Operators

OperatorUseReturns true if
>op1 > op2op1 is greater than op2
>=op1 >= op2op1 is greater than or equal to op2
<op1 < op2op1 is less than to op2
<=op1 <= op2op1 is less than or equal to op2
==op1 == op2op1 and op2 are equal
!=op1 != op2op1 and op2 are not equal

Table 3.4. Conditional Operators

OperatorUseReturns true if
&&op1 && op2op1 and op2 are both true
||op1 || op2op1 or op2 is true
!! opop is false

Audio in Portuguese

Table 3.5. Bitwise Operators

OperatorUseOperation
>>op1 >> op2shift bits of op1 right by distance op2
<<op1 << op2shift bits of op1 left by distance op2
>>>op1 >>> op2shift bits of op1 right by distance op2 (unsigned)
&op1 & op2bitwise and
|op1 | op2bitwise or
^op1 ^ op2bitwise xor
~~ opbitwise complement

You use the assignment operator, =, to assign one value to another.

[Caution]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:

Figure 3.2. Memory Structure: 2 pointers

Memory Structure: 2 pointers

If the Assignment operator is used:

car2 = car1;

The car2 variable is pointed to the same object as car1 variable:

Figure 3.3. Memory Structure: Same pointer

Memory Structure: Same pointer

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.

Audio in Portuguese

Table 3.6. Short Cut for the Assignment Operator

OperatorUseEquivalent to
+=op1 += op2op1 = op1 + op2
-=op1 -= op2op1 = op1 - op2
*=op1 *= op2op1 = op1 * op2
/=op1 /= op2op1 = op1 / op2
-=op1 -= op2op1 = op1 - op2
|=op1 |= op2op1 = op1 | op2
^=op1 ^= op2op1 = op1 ^ op2
<<=op1 <<= op2op1 = op1 << op2
>>=op1 >>= op2op1 = op1 >> op2
>>>=op1 >>>= op2op1 = op1 >>> op2

Audio in Portuguese