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.
int myAge;
myAge = 18;
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 type int
.
- If one or more of the operands are of type
double
, the result is of type double
.
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 / 2
results in 3
, the decimal portion is not included.
4 / 2
results in 2
, 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 / 2
results in 3.5
. Similarly, 7 / 2.0
and 7.0 / 2.0
will also result in 3.5
.
4.0 / 2
results in 2.0
. Similarly, 4 / 2.0
and 4.0 / 2.0
will also result in 2.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?
Modulus divsion give the remainder when two numbers are divided. For example:
7 % 2
results in 1
, since 2
divides into 7
, 3
whole times with a remainder of 1
.
17 % 3
results in 2
, since 3
divides into 17
, 5
whole times with a remainder of 2
.
4 % 2
results is 0
, since 2
divides into 4
, 2
whole times with no remainder.
2 % 3
results in 2
, since 3
divides into 2
, 0
whole times and 2
is 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?
Resources
Next Learn Tutorial
Learn: Applying the Order of Operations