Operators in Java are special symbols or keywords used to perform operations on variables and values. They can be classified into various types based on their functionality. Two of the most commonly used categories are arithmetic operators and assignment operators.
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. Here are the arithmetic operators in Java:
Addition (+): Adds two operands.
int a = 5;
int b = 3;
int sum = a + b; // sum is 8
Subtraction (): Subtracts the second operand from the first.
int difference = a - b; // difference is 2
Multiplication (): Multiplies two operands.
int product = a * b; // product is 15
Division (/): Divides the first operand by the second. Note that if both operands are integers, the result is an integer (integer division).
int quotient = a / b; // quotient is 1 (integer division)
float quotientFloat = (float) a / b; // quotientFloat is 1.6667 (floating-point division)
Modulus (%): Returns the remainder when the first operand is divided by the second.
int remainder = a % b; // remainder is 2
Unary Plus (+): Indicates a positive value (usually optional since values are positive by default).
int positive = +a; // positive is 5
Unary Minus (): Negates the value of the operand.
int negative = -a; // negative is -5
Assignment operators are used to assign values to variables. The most common assignment operator is the simple assignment operator =, but there are several compound assignment operators that combine arithmetic operations with assignment.
Simple Assignment (=): Assigns the value on the right to the variable on the left.
int x = 10; // Assigns 10 to x
Addition Assignment (+=): Adds the value on the right to the variable on the left and assigns the result to the variable on the left.
x += 5; // Equivalent to x = x + 5; x is now 15
Subtraction Assignment (=): Subtracts the value on the right from the variable on the left and assigns the result to the variable on the left.
x -= 3; // Equivalent to x = x - 3; x is now 12
Multiplication Assignment (=): Multiplies the variable on the left by the value on the right and assigns the result to the variable on the left.
x *= 2; // Equivalent to x = x * 2; x is now 24
Division Assignment (/=): Divides the variable on the left by the value on the right and assigns the result to the variable on the left.
x /= 4; // Equivalent to x = x / 4; x is now 6
Modulus Assignment (%=): Performs the modulus operation on the variable on the left with the value on the right and assigns the result to the variable on the left.
x %= 5; // Equivalent to x = x % 5; x is now 1