Arithmetic operators

In Java there are the usual arithmetic operators, as in most other programming languages, namely addition, subtraction, multiplication, division and the remainder operator (modulo). In addition, there are the one-digit operators for positive and negative sign as well as the increment and decrement operators. The arithmetic operators expect numeric operands and return a numeric return value.

OperatorDescriptionPriority
+Positive sign1
Negative sign1
++Increment1
Decrement1
*Multiplication2
/Division2
%Rest (modulo)2
+Addition3
Subtraction3

Code Explanation

LineDescription
3 – 5Initializes the integer variables
a with value 6 and b with value 4,
the variable c of type long with value 7
and the variable of type double with value 0
7 – 8Outputs the starting values
10 – 13Divide variable a by b. The result is automatically rounded, because the values are integers
15 – 17Divides variable a with variable b and performs a type conversion beforehand (int to double)
19 – 20Assigns the value of variable c to variable a as an integer
public class BasicArithmeticExpressions {
    public static void main(String[] args) {
        int a = 6, b = 4;
        long c = 7;
        double z = 0;

        System.out.println("Starting Values");
        System.out.println("a = " + a + "\nb = " + b + "\nc = " + c + "\nz = " + (int) z);

        System.out.println("Calculations");
        // works, but wrong result because of integer
        z = a / b;
        System.out.println("z = " + a + " / " + b + " = " + z + "\n");

        // An explicit type conversion is carried out with the cast operator
        z = (double) a / (double) b;
        System.out.println("z = " + (double) a + " / " + (double) b + " = " + z);

        a = (int) c;
        System.out.println("a = " + a);
    }
}
Output
Starting Values
a = 6
b = 4
c = 7
z = 0

Calculations
z = 6 / 4 = 1.0
z = 6.0 / 4.0 = 1.5
a = 7