Arithmetic Operators in Java
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators work with numeric data types like int, float, double, etc.
List of Arithmetic Operators:
| Operator | Name | Meaning | Example | Output |
|---|---|---|---|---|
| + | Addition | Adds two values | 10 + 5 | 15 |
| - | Subtraction | Subtracts second value from first | 10 - 5 | 5 |
| * | Multiplication | Multiplies two values | 10 * 5 | 50 |
| / | Division | Divides first value by second | 10 / 2 | 5 |
| % | Modulus (Remainder) | Gives remainder after division | 10 % 3 | 1 |
Example 1: Basic Arithmetic Operations
class ShikshaSanchar {
public static void main(String[] args) {
int a = 20;
int b = 6;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
Output:
Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3
Modulus: 2
Explanation:
- 20 + 6 = 26
- 20 - 6 = 14
- 20 * 6 = 120
- 20 / 6 = 3 (Integer division: fractional part is discarded)
- 20 % 6 = 2 (Remainder after dividing 20 by 6)
Example 2: Division with Decimal Values
class ShikshaSanchar {
public static void main(String[] args) {
double x = 10;
double y = 4;
System.out.println("Exact Division: " + (x / y));
}
}
Output:
Exact Division: 2.5
Explanation:
- Since both operands are double, division result is also a decimal.
Easy Notes:
- If you divide two whole numbers (integers), the decimal part gets removed. To get the correct decimal answer, use double type instead of int.
- The % (modulus) operator is helpful:
- To check if a number is even: num % 2 == 0
- For repeating tasks like going in a loop again after a certain count.
Summary:
- Arithmetic operators perform mathematical calculations.
- +, -, *, /, and % are the five arithmetic operators.
- Use appropriate data types to avoid unexpected results (e.g., integer vs. floating-point division).