How to Use Arithmetic Operators in Java: Syntax and Examples
In Java, you use
+, -, *, /, and % as arithmetic operators to perform addition, subtraction, multiplication, division, and modulus operations respectively. These operators work with numeric types like int and double to calculate values in expressions.Syntax
Java uses simple symbols called arithmetic operators to do math on numbers. Here are the main ones:
+for addition-for subtraction*for multiplication/for division%for remainder (modulus)
You write expressions like result = a + b; where a and b are numbers.
java
int a = 5; int b = 3; int sum = a + b; int difference = a - b; int product = a * b; int quotient = a / b; int remainder = a % b;
Example
This example shows how to use all arithmetic operators with two numbers and prints the results.
java
public class ArithmeticExample { public static void main(String[] args) { int a = 15; int b = 4; 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: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
Common Pitfalls
One common mistake is dividing integers and expecting a decimal result. In Java, dividing two int values gives an integer result by cutting off the decimal part.
To get a decimal result, convert one number to double before dividing.
java
int a = 7; int b = 2; // Wrong: integer division truncates decimal int result1 = a / b; // result1 is 3 // Right: convert to double for decimal division double result2 = (double) a / b; // result2 is 3.5
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 5 / 3 | 1 (integer division) |
| % | Modulus (remainder) | 5 % 3 | 2 |
Key Takeaways
Use +, -, *, /, and % to perform basic math operations in Java.
Integer division truncates decimals; cast to double for decimal results.
Arithmetic operators work with numeric types like int and double.
Remember % gives the remainder after division.
Always use parentheses to clarify complex expressions.