Arithmetic operators are fundamental in Java for performing basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators are used extensively in computations, algorithms, and data processing tasks. Understanding how they work is essential for any Java programmer.
+
)The addition operator adds two operands.
int a = 10;
int b = 5;
int result = a + b; // result is 15
-
)The subtraction operator subtracts the second operand from the first.
int a = 10;
int b = 5;
int result = a - b; // result is 5
*
)The multiplication operator multiplies two operands.
int a = 10;
int b = 5;
int result = a * b; // result is 50
/
)The division operator divides the first operand by the second. When both operands are integers, the result is an integer (the fractional part is discarded).
int a = 10;
int b = 5;
int result = a / b; // result is 2
For floating-point division, at least one of the operands should be a floating-point number.
double a = 10.0;
double b = 4.0;
double result = a / b; // result is 2.5
%
)The modulus operator returns the remainder when the first operand is divided by the second.
int a = 10;
int b = 3;
int result = a % b; // result is 1
Here is a complete Java program that demonstrates the use of arithmetic operators:
public class ArithmeticOperatorsDemo {
public static void main(String[] args) {
int a = 15;
int b = 4;
// Addition
int addition = a + b;
System.out.println("Addition of " + a + " and " + b + " = " + addition);
// Subtraction
int subtraction = a - b;
System.out.println("Subtraction of " + a + " and " + b + " = " + subtraction);
// Multiplication
int multiplication = a * b;
System.out.println("Multiplication of " + a + " and " + b + " = " + multiplication);
// Division (integer)
int division = a / b;
System.out.println("Division of " + a + " by " + b + " = " + division);
// Modulus
int modulus = a % b;
System.out.println("Modulus of " + a + " and " + b + " = " + modulus);
// Floating-point division
double c = 15.0;
double d = 4.0;
double floatDivision = c / d;
System.out.println("Floating-point division of " + c + " by " + d + " = " + floatDivision);
}
}