0
0
JavaHow-ToBeginner · 3 min read

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

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 31 (integer division)
%Modulus (remainder)5 % 32

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.