Introduction to Arithmetic Expressions
Assignments
The assignment operator (=) is used to initialize a variable and to update it to a new value.
The variable that is being assigned a value is on the left side of the assignment operator and the value that is being assigned is on the right.
Expressions
In analyzing data, we will need to write expressions to do computations. The following arithmetic operators are used in expressions:
+for addition-for subtraction*for multiplication/for division%for modulus division
When using these operators, the resulting type depends on the data type of the operands.
- If both operands are of type
int, the result is of typeint. - If one or more of the operands are of type
double, the result is of typedouble.
This means that division functions in two different ways.
- If both operands are of type
int, the result truncates (removes) any remainder. This is considered integer division. For example:7 / 2results in3, the decimal portion is not included.4 / 2results in2, there is no remainder in this case.
- If one or both operands are of type
double, the result includes the remainder. For example:7.0 / 2results in3.5. Similarly,7 / 2.0and7.0 / 2.0will also result in3.5.4.0 / 2results in2.0. Similarly,4 / 2.0and4.0 / 2.0will also result in2.0.
Your Turn
Let's try this in the Java Playground.
- Add the expressions above to the Java playground
- Create variables to store the result of each expressions. What data type should you use for each of the following?
- 7.0 / 3
- 5 / 3
- 9 / 4.0
Modulus divsion give the remainder when two numbers are divided. For example:
7 % 2results in1, since2divides into7,3whole times with a remainder of1.17 % 3results in2, since3divides into17,5whole times with a remainder of2.4 % 2results is0, since2divides into4,2whole times with no remainder.2 % 3results in2, since3divides into2,0whole times and2is the remainder.
Your Turn
Let's try this in the Java Playground.
- Add each of the expressions above to the playground.
- Create variables to store the result of each expression. What data type should you use for each expression?