What is Assignment Operators in
Java?
Assignment operators in Java are used to assign values to variables. The most basic assignment operator is the equal sign =. In addition to the basic assignment, Java provides several compound assignment operators that combine an arithmetic operation with assignment.
1. Basic Assignment Operator (=) #
The = operator assigns the value on the right to the variable on the left.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10; // Assigns 10 to variable a
System.out.println("a = " + a);
}
}
Output:
a = 10
2. Compound Assignment Operators
These operators perform an arithmetic operation on the variable and then assign the result to that variable.
a. Add and Assign (+=) #
This operator adds the right operand to the left operand and assigns the result to the left operand.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10;
a += 5; // Equivalent to a = a + 5
System.out.println("a = " + a);
}
}
Output:
a = 15
b. Subtract and Assign (-=) #
This operator subtracts the right operand from the left operand and assigns the result to the left operand.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10;
a -= 3; // Equivalent to a = a - 3
System.out.println("a = " + a);
}
}
Output:
a = 7
c. Multiply and Assign (*=) #
This operator multiplies the left operand by the right operand and assigns the result to the left operand.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10;
a *= 2; // Equivalent to a = a * 2
System.out.println("a = " + a); // Output: a = 20
}
}
d. Divide and Assign (/=) #
This operator divides the left operand by the right operand and assigns the result to the left operand.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10;
a /= 2; // Equivalent to a = a / 2
System.out.println("a = " + a);
}
}
Output:
a = 5
e. Modulus and Assign (%=)
This operator takes the modulus of the left operand by the right operand and assigns the result to the left operand.
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10;
a %= 3; // Equivalent to a = a % 3
System.out.println("a = " + a);
}
}
Output:
a = 1
Summary
Assignment operators in Java provide a convenient way to update the value of a variable. By using compound assignment operators, you can write more concise and readable code.