Java Tutorial Java Advanced Java References

Java - arithmetic operators example



The example below shows the usage of arithmetic operators - addition(+), subtraction(-), multiply(*), division(/) and modulo(%) operators.

public class MyClass {
  public static void main(String[] args) {
    float a = 25f;
    float b = 10f;

    System.out.println("a = "+a+", b = "+b+"\n");

    //Add a and b
    float result_add = a + b;
    System.out.println("a + b = "+result_add);

    //Subtract b from a
    float result_sub = a - b;
    System.out.println("a - b = "+result_sub);

    //Multiply a and b
    float result_mul = a * b;
    System.out.println("a * b = "+result_mul);

    //Divide a by b
    float result_div = a / b;
    System.out.println("a / b = "+result_div);

    //return division remainder 
    float result_modulo = a % b;
    System.out.println("a % b = "+result_modulo);  
  }
}

The output of the above code will be:

a = 25.0, b = 10.0

a + b = 35.0
a - b = 15.0
a * b = 250.0
a / b = 2.5
a % b = 5.0

❮ Java - Operators