Casting VariablesΒΆ

In DrJava try typing the following in the interactions pane and hit return or enter after each line. DrJava will automatically print the result of an expression when you hit enter in the interactions pane.

1 / 3
1.0 / 3
1 / 3.0
(double) 1 / 3

Do you get the same answer for each of these? If not, why not?

3-5-1: What is printed in DrJava when you type 1 / 3 and hit enter?

3-5-2: What is printed in DrJava when you type 1.0 / 3 and hit enter?

Java assumes that if you are doing division with integers that you want an integer result and it will throw away any fractional part (part after the decimal point). But, if you use a mixture of integers (int) and floating point (double) numbers Java will assume that you want a floating point result. If you have integers and you want a floating point result from some mathematical operation cast one of the integers to a double using (double) as shown above. By casting we don’t mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the “shape” (or type) of the variable to the right of the cast to the specified type.


Figure 3: Casting a pot in clay.

Is the result of 1.0 divided by 3 correct? Actually, Java limits the number of digits you can save for any double number to about 14-15 digits. You should be aware that the accuracy of any calculation on a computer is limited by the fact that computers can only hold a limited number of digits.

Check your understanding

3-5-3: True or false: Java rounds up automatically when you do integer division.

3-5-4: True or false: casting always results in a double type.

3-5-5: Which of the following returns the correct average when 3 values had been added to an integer total?