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.
Operator | Description | Priority |
---|---|---|
+ | Positive sign | 1 |
– | Negative sign | 1 |
++ | Increment | 1 |
— | Decrement | 1 |
* | Multiplication | 2 |
/ | Division | 2 |
% | Rest (modulo) | 2 |
+ | Addition | 3 |
– | Subtraction | 3 |
Line | Description |
---|---|
3 – 5 | Initializes the integer variables a with value 6 and b with value 4,the variable c of type long with value 7and the variable of type double with value 0 |
7 – 8 | Outputs the starting values |
10 – 13 | Divide variable a by b . The result is automatically rounded, because the values are integers |
15 – 17 | Divides variable a with variable b and performs a type conversion beforehand (int to double ) |
19 – 20 | Assigns 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);
}
}
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