Explanation
There are various arithmetic and assignment operators for performing mathematical operations and assigning values to variables. Here are some of the most common operators along with examples:
Arithmetic Operators:
-
Addition ‘ + ‘: Adds two operands.
int result = 5 + 3; // result is now 8
-
Subtraction ‘ - ‘: Subtracts the right operand from the left operand.
int result = 10 - 4; // result is now 6
-
Multiplication ’ * ‘: Multiplies two operands.
int result = 3 * 5; // result is now 15
-
Division ‘ / ‘: Divides the left operand by the right operand.
double result = 12.0 / 4; // result is now 3.0
-
Modulus ‘ % ‘: Returns the remainder of the division of the left operand by the right operand.
int result = 15 % 4; // result is now 3
Assignment Operators:
Assignment ‘= ‘: Assigns the value of the right operand to the left operand.
int x = 5; // x is assigned the value 5
Addition Assignment ‘ += ‘: Adds the right operand to the left operand and assigns the result to the left operand.
int x = 5;
x += 3; // x is now 8
Subtraction Assignment ‘ -= ‘: Subtracts the right operand from the left operand and assigns the result to the left operand.
int x = 10;
x -= 4; // x is now 6
Multiplication Assignment ’ *=’ : Multiplies the left operand by the right operand and assigns the result to the left operand.
int x = 3;
x *= 5; // x is now 15
Division Assignment ’ /=’ : Divides the left operand by the right operand and assigns the result to the left operand.
double x = 12.0;
x /= 4; // x is now 3.0
Modulus Assignment ‘ %= ’: Calculates the modulus of the left operand and assigns the result to the left operand.
int x = 15;
x %= 4; // x is now 3