The shortcut assignment operator can be used for all Arithmetic Operators i.e. You can use this style with all arithmetic operators.
Assignment Operators with examples
Operator | Meaning and example |
= | Assignment operator Example a = b b is evaluated and a set to this value. |
+=, -=, *=, /=, %= | Arithmetic operation and then assignment Example a -= b is equivalent to a = a - b |
&=, |=, ^= | Bitwise operation and then assignment Example a &= b is equivalent to a = a & b |
<<=, >>=, >>>= | Shift operations and then assignment Example a <<= b is equivalent to a = a << b |
Examples of Assignment Operators
Example 1 : Program that displays use of all assignment and shortcut assignment operators i.e. =, +=, -=, *=, /=, %=, &= etc
class AssignOptrDemo
{
public static void main(String[] args)
{
int a = 10, b = 15, c = 15;
System.out.println("Assignment and shortcut assignment operators");
System.out.println(" a = " + (a = 15));
System.out.println(" Addition = " + (a += b));
System.out.println(" Subtraction = " + (c -= b));
System.out.println(" Division = " + (a /= 2));
System.out.println(" Multiplication = " + (a *= 2));
}
}
Output
Assignment and shortcut assignment operators
a = 15
Addition = 30
Subtraction = 0
Division = 15
Multiplication = 30