Java Assignment Operators
Assignment operators are used to assign a value to a variable. The Java programming language features a number of assignment operators, which can be used to perform a variety of operations before assignment.
The simple assignment operator uses an equals ‘=‘ symbol.
The following table shows the assignment operators available in Java:
Operator | Example | Description |
= | a = 10 | Assign |
+= | a += 5 | Add and assign |
-= | a -= 5 | Subtract and assign |
*= | a *= 5 | Multiply and assign |
/= | a /= 5 | Divide and assign |
%= | a %= 5 | Remainder and assign |
>>= | a >>= 2 | Right-shift and assign |
<<= | a << 2 | Left-shift and assign |
&= | a &= b | Bitwise AND, and assign |
|= | a |= b | Bitwise OR (inclusive) and assign |
^= | a ^= b | Bitwise exclusive OR (XOR) and assign |
Simple Assignment Operator
The simple assignment operator is used to assign a value to a variable. It uses the equal ‘=’ symbol.
int a = 5;
Other Assignment Operators
There are a number of other assignment operators, which allow us to perform mathematical or bitwise operations on a value prior to assignment.
For example, the ‘+=’ operator allows us to add to and re-assign a value to a variable:
int a = 5;
a += 5; // a is now 10
In the above example, the expression ‘a +=5’ results in the value of the a variable being increased by 5.
We can use many of the other assignment operators in a similar fashion:
int a = 10;
a -= 5; // a is now 5
a *= 4; // a is now 20
a /= 2; // a is now 10
a %= 3; // a is now 1 - 10 / 3 is 3, remainder of 1