Introduction
In Java, assignment operators are used to assign values to variables. In addition to the simple assignment (=), Java provides shorthand assignment operators that combine arithmetic operations with assignment. These operators make the code shorter, cleaner, and easier to read. This tutorial explains the most commonly used assignment operator shorthands in Java.
Code: Assignment Operators Shorthand Example
public class AssignmentOperatorsExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition assignment
a += b; // Equivalent to a = a + b
System.out.println("After a += b, a = " + a);
// Subtraction assignment
a -= b; // Equivalent to a = a - b
System.out.println("After a -= b, a = " + a);
// Multiplication assignment
a *= b; // Equivalent to a = a * b
System.out.println("After a *= b, a = " + a);
// Division assignment
a /= b; // Equivalent to a = a / b
System.out.println("After a /= b, a = " + a);
// Modulus assignment
a %= b; // Equivalent to a = a % b
System.out.println("After a %= b, a = " + a);
}
}
Explanation of Each Code Part
1. Variable Declaration
int a = 10; int b = 5;
- Two integer variables
aandbare declared and initialized. ais assigned 10,bis assigned 5.
2. Addition Assignment (+=)
a += b; // a = a + b
- Adds the value of
btoaand stores the result ina. - Shorthand for
a = a + b.
3. Subtraction Assignment (-=)
a -= b; // a = a - b
- Subtracts
bfromaand stores the result ina. - Shorthand for
a = a - b.
4. Multiplication Assignment (*=)
a *= b; // a = a * b
- Multiplies
abyband stores the result ina. - Shorthand for
a = a * b.
5. Division Assignment (/=)
a /= b; // a = a / b
- Divides
abyband stores the result ina. - Shorthand for
a = a / b.
6. Modulus Assignment (%=)
a %= b; // a = a % b
- Calculates the remainder of
adivided byband stores it ina. - Shorthand for
a = a % b.
Conclusion
Shorthand assignment operators in Java:
- Combine arithmetic operations and assignment in a concise way.
- Make the code easier to read and write.
- Can be used with integers, floats, doubles, and other numeric types.
By using these operators, you can simplify arithmetic operations on variables and reduce repetitive code.