Now, we can start working more with these data types. In this section, we're going to focus on the two numeric types: int and double.
For addition, subtraction, and multiplication, equations can be input as you would input them into your calculator. Variables are used to assign the answers to the correct equation.
int a = 1 + 2;
double b = 1.0 + 3.5;
int c = 3 - 5;
double d = 24 * 1.0
a = 3
b = 4.5
c = -2
d = 24.0
The equal sign, which is the assignment operator, can be used to change the value of the variable or other expressions. It evaluates the expression first and stores the final value in the variable.
If an operation has two integers, then the result is an integer. If an operation has at least one double, then the result is a double.
There is also a modulo operator, denoted by %. When a user inputs a % b, the program reports the integer remainder of a divided by b, where a and b are both integers and b is positive. We will only talk about modulo with positive values of a because once a is negative, the math becomes much more complicated. A few examples are below:
int a = 4 % 2;
int b = 10 % 3;
int c = 3 % 5;
a = 0 (4 = 2 * 2 + **0**)
b = 1 (10 = 3 * 3 + **1**)
c = 3 (3 = 0 * 5 + **3**)
Things get a bit more complicated with division. Remember that operations with two integers return an integer, and if there is at least one double, it returns a double. Here is an example of each:
int a = 5 / 2;
double b = 5 / 2.0
a = 2
b = 2.5
Integer division returns only the whole number quotient, while the double division returns the actual quotient as a decimal.
Java follows the regular order of operations that you learned in algebra, with the inclusion of modulo with multiplication and division. Here is a table of the order of operations with operators from highest to lowest precedence:
Courtesy of Stack Overflow
Here is some practice with order of operations. Remember the difference between double division and integer division. Find the value of each variable in the following:
int a = 3 + 4 / 3 * (4-1);
double b = (3 * 5 / 2) / (2.0 + 8);
int c = 4 % 3 + 2 * 5 / 4;
int d = (3 * 5 / 2) / (2 + 8);
a = 3 + 4 / 3 * (4 - 1) = 3 + 4 / 3 * 3 = 3 + 1 * 3 = 3 + 3 = **6**
b = (3 * 5 / 2) / (2.0 + 8) = (15 / 2) / (10.0) = (7) / (10.0) = **0.7**
c = 4 % 3 + 2 * 5 / 4 = 1 + 2 * 5 / 4 = 1 + 10 / 4 = 1 + 2 = **3**
d = (3 * 5 / 2) / (2 + 8) = (15 / 2) / (10) = (7) / (10) = **0**