Java assignment operators
Created By: chatGPT
Assignment operators in Java are used to assign values to variables. The simplest assignment operator is the basic equals sign (
=
), but there are several combined operators that perform arithmetic operations along with the assignment. Here’s a brief overview of these operators.1. The basic assignment operator sets the value of a variable. For example:
int a = 5;
2. The addition assignment operator (
+=
) adds the right operand to the left operand and assigns the result to the left operand.a += 3; // equivalent to a = a + 3
3. The subtraction assignment operator (
-=
) subtracts the right operand from the left operand and assigns the result to the left operand.a -= 2; // equivalent to a = a - 2
4. The multiplication assignment operator (
*=
) multiplies the left operand by the right operand and assigns the result to the left operand.a *= 4; // equivalent to a = a * 4
5. The division assignment operator (
/=
) divides the left operand by the right operand and assigns the result to the left operand.a /= 2; // equivalent to a = a / 2
6. The modulus assignment operator (
%=
) takes the modulus using two operands and assigns the result to the left operand.a %= 3; // equivalent to a = a % 3
In summary, these operators help to streamline code by combining arithmetic operations with assignment in a more concise manner. Here is an example of using these assignment operators in a Java program.
public class AssignmentExample {
public static void main(String[] args) {
int a = 5;
a += 3; // a is now 8
a -= 2; // a is now 6
a *= 4; // a is now 24
a /= 2; // a is now 12
a %= 5; // a is now 2
System.out.println(a); // Output: 2
}
}