In Introduction to Arithmetic Expressions tutorial, we learned that there are two different types of division.
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
.
There are often times when you have two int
values or variables and want to compute division and have the result include the remainder. There are also times when one of the values is a double
and we need the whole part of the division.
For example, maybe you want to compute your average for a class. You have two int
values: the sum of all the grades and the number of grades that you have. When we compute the average of the the two int
values, it will truncate the result, essentially always rounding down.
Let's try this in the Java Playground. Be sure to toggle the console to "Detailed Output".
Instead, you might want to have the real-number average. To do this, you can cast one or both of the operands to be a double
. Casting Conversions converts the type of an expression to the type specified. It is done by placing the desired type in parenthesis prior to the expression.
Let's try this in the Java Playground. Be sure to toggle the console to "Detailed Output".
When we type cast from an int
to a double
, this is considered a widening conversion since the int
value fits into the double
type without any loss of data.
When we type cast from a double
to an int
, this is considered a narrowing conversion since the double
value might need to be truncated to fit into the int
type thereby losing some data. For example:
Let's try this in the Java Playground. Be sure to toggle the console to "Detailed Output".