0
0
Javaprogramming~5 mins

Arithmetic operators in Java

Choose your learning style9 modes available
Introduction

Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, divide, and find remainders easily.

Calculating the total price of items in a shopping cart.
Finding the average score of a student.
Counting how many days are left until an event.
Splitting a bill evenly among friends.
Converting units, like inches to centimeters.
Syntax
Java
result = value1 + value2;  // addition
result = value1 - value2;  // subtraction
result = value1 * value2;  // multiplication
result = value1 / value2;  // division
result = value1 % value2;  // remainder (modulus)

Use + to add numbers.

Use % to get the remainder after division.

Examples
Adds 5 and 3 to get 8.
Java
int sum = 5 + 3;  // sum is 8
Subtracts 4 from 10 to get 6.
Java
int difference = 10 - 4;  // difference is 6
Multiplies 7 by 2 to get 14.
Java
int product = 7 * 2;  // product is 14
Divides 20 by 5 to get 4, and finds remainder of 20 divided by 3 which is 2.
Java
int quotient = 20 / 5;  // quotient is 4
int remainder = 20 % 3;  // remainder is 2
Sample Program

This program shows how to use all the basic arithmetic operators with two numbers, 15 and 4. It prints the results of each operation.

Java
public class ArithmeticOperatorsDemo {
    public static void main(String[] args) {
        int a = 15;
        int b = 4;

        int sum = a + b;
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;

        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
        System.out.println("Remainder: " + remainder);
    }
}
OutputSuccess
Important Notes

Division between two integers gives an integer result, cutting off any decimal part.

Use parentheses () to control the order of operations if needed.

Summary

Arithmetic operators let you do basic math in Java.

They include +, -, *, /, and %.

Remember integer division drops decimals.