Operators

Java Program to Demonstrate Arithmetic Operators

A Java program to demonstrate the usage of arithmetic operators.

Problem Description

Write a Java program to perform basic arithmetic operations: addition, subtraction, multiplication, division, and modulus.

Code

ArithmeticOperators.java
public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    }
}

Output

a + b = 15
a - b = 5
a * b = 50
a / b = 2
a % b = 0

Explanation

  1. + (Addition): Adds two operands.
  2. - (Subtraction): Subtracts the second operand from the first.
  3. * (Multiplication): Multiplies two operands.
  4. / (Division): Divides the numerator by the denominator.
  5. % (Modulus): Returns the remainder of the division.

Try Yourself

Practice these variations to master arithmetic operators.

  1. Remainder: Change b to 3. What is a % b?
  2. Integer Division: Calculate 5 / 2 and print it. Why is it 2 and not 2.5?
  3. Floating Point: Change a to 10.0 (double). Now what is a / b?
  4. Order of Operations: Print the result of 5 + 10 * 2. Is it 30 or 25?
  5. Brain Twister: Try to divide by zero (10 / 0). What happens?