We use Assignment operators to assign values to variables.
int x = 10;
In the above statement, we use the assignment operator ( = ) to assign the value 10 to x.
Shorthand Operators
Statements like this:
a = a + 10;
are used a lot in programs. Java provides shorthand operators to combine the arithmetic and assignment operator into a single operator and write the above statement like this:
a += 10;
Both these statements are equivalent. They add 10 to a and assign the value back to a. The second statement uses the shorthand operator and is a little simple and saves a bit of typing.
There are shorthand operators for all arithmetic binary operators. The table below lists some of the shorthand operators in Java:
Operator | Example | Same As |
---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
Let’s look at a BlueJ program to see some examples of Shorthand operator’s usage:
public class ShorthandOp
{
public void demoShorthandOp() {
int x = 10, y = 20, z = 30;
x += 20; //Same as x = x + 20
y *= 3; //Same as y = y * 3
z -= 15; //Same as z = z - 15
z += x * y; //Same as z = z + (x * y)
z %= 7; //Same as z = z % 7
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
}
Here is the output of the program: