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 Example

The code is a basic Java program that demonstrates some of the arithmetic expressions in Java programming language.

The program starts by defining three integer variables a, b, and c, and one floating-point variable z. The values of a and b are assigned 6 and 4 respectively, the value of c is assigned 7, and the value of z is assigned 0.

Next, the values of the variables are printed to the console using the System.out.println() method.

The program then performs several arithmetic calculations and type conversions, and the results of these calculations are also printed to the console.

First, the division of a by b is performed and assigned to z. However, since both a and b are integers, integer division is performed, and the result is a whole number.

Next, an explicit type conversion is performed on a and b by casting them to double data type. The division of a and b is then performed, and the result, which is a floating-point number, is assigned to z.

Finally, c, which is of type long, is cast to int and assigned to a.

The program demonstrates how type conversions and arithmetic expressions work in Java programming language.

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