Core Java Fundamentals ยท Operators

Arithmetic Operators

Learn the fundamental arithmetic operators in Java to perform mathematical calculations like addition, subtraction, multiplication, division, and finding remainders.

ArithmeticDemo.java

public class ArithmeticDemo {
    public static void main(String[] args) {
        // Declare and initialize two integer variables
        int a = 20;
        int b = 7;

        // 1. Addition (+)
        int sum = a + b;
        System.out.println("Sum: " + sum);

        // 2. Subtraction (-)
        int difference = a - b;
        System.out.println("Difference: " + difference);

        // 3. Multiplication (*)
        int product = a * b;
        System.out.println("Product: " + product);

        // 4. Integer Division (/)
        int quotient = a / b;
        System.out.println("Integer Quotient: " + quotient);

        // 5. Floating-Point Division
        double preciseQuotient = (double) a / b;
        System.out.println("Precise Quotient: " + preciseQuotient);

        // 6. Modulus (%) - Remainder of a division
        int remainder = a % b;
        System.out.println("Remainder: " + remainder);
    }
}

Step by step

  1. We declare an integer variable a and assign it the value 20. This value is stored in memory.
  2. Next, we declare another integer variable b and assign it the value 7.
  3. The addition operator + adds the values of a and b (20 + 7). The result, 27, is stored in a new variable sum.
  4. We print the result of the addition. The string "Sum: " is created in the String Pool and concatenated with the value of sum.
  5. The subtraction operator - subtracts b from a (20 - 7). The result, 13, is stored in difference.
  6. We print the difference. The string "Difference: " is added to the String Pool.
  7. The multiplication operator * multiplies a and b (20 * 7). The result, 140, is stored in product.
  8. We print the product. The string "Product: " is added to the String Pool.
  9. The division operator / performs integer division when both operands are integers. 20 / 7 is 2.857..., but since it is integer division, the decimal part is truncated. The result is 2.
  10. The truncated integer quotient is printed.
  11. To get a precise decimal result, we cast one of the integers to a double. (double) a temporarily treats a as 20.0. Now, the division is 20.0 / 7, which results in a double value.
  12. The precise floating-point result is printed.
  13. The modulus operator % gives the remainder of a division. 20 divided by 7 is 2 with a remainder of 6. This operator is very useful for tasks like checking for even or odd numbers.
  14. Finally, we print the remainder.