1.6. Casting and Ranges of Variables

In Java, type casting is used to convert variables from one type to another. 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.

../_images/casting.jpg

Figure 1: Casting a pot in clay.

Run this code to find how Java handles division and what casting can do to the results.

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.

Values of type double can be rounded to the nearest integer by formulas like the following. If you have a number like 3.33 and you add 0.5 to it, you get 3.83 and then casting it to an int throws away what’s after the decimal point, just leaving 3.

double number = 10 / 3;
int nearestInt = (int)(number + 0.5);
double negNumber = -10 / 3;
int nearestNegInt = (int)(negNumber – 0.5);

What happens to repeating decimal numbers like 3.333333…? 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.

For example, int values are stored in 4 bytes of memory. There is an Integer.MAX_VALUE defined as 2147483647 and an Integer.MIN_VALUE defined as -2147483648. If you try to store any number larger or smaller than these numbers in an int variable, it will result in an error called integer overflow. Try it below.

Although it’s not on the exam, you can format long decimal numbers to just show 2 digits after the decimal point with the following code:

exercise Check your understanding

    1-6-1: True or false: Java rounds up automatically when you do integer division.

  • true
  • Did you try this out in Active Code? Does it work that way?
  • false
  • Java throws away any values after the decimal point if you do integer division. It does not round up automatically.

    1-6-2: True or false: casting always results in a double type.

  • true
  • Try casting to int instead of double. What does that do?
  • false
  • Casting results in the type that you cast to. However, if you can't really cast the value to the specified type then you will get an error.

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

  • (double) (total / 3);
  • This does integer division before casting the result to double so it loses the fractional part.
  • total / 3;
  • When you divide an integer by an integer you get an integer result and lose the fractional part.
  • (double) total / 3;
  • This will convert total to a double value and then divide by 3 to return a double result.

1.6.1. groupwork Programming Challenge

This would be a good project to work together in pairs, and switch drivers (who has control of the keyboard in pair programming) after every line of code. In the code below, type in three made up int grades and then sum and average them. Use casting to report the result as a double. For example, if the grades are 90, 100, and 94, the sum of the three numbers is 90 + 100 + 94 = 284, and the average is the sum 284 divided by 3 which casted to a double is 94.666667. You should use your variables instead of the numbers in your formulas. Follow the pseudocode below.

Your teacher may suggest that you use a Java IDE like repl.it for this challenge so that you can use input to get these values using the Scanner class.

If you get done early with this challenge, here’s something else fun you can do in Java, although it’s not covered in the AP exam. Java was one of the first programming languages to use Unicode for its characters. Unicode is an international standard where each letter in any alphabet is represented by a number. Unicode uses hex code (a base 16 code that uses the digits 0-9 and the letters A-F for 10-15), but you can give Java an equivalent decimal number and type cast it to the type char (for character) to show the unicode character. Try the following program which prints out Chinese characters. Look up other characters at this Unicode Lookup site and print them out in the Active Code window below by using the decimal number (see Dec column in site) and type casting to char. Can you print out a letter from 3 different languages?

1.6.2. Summary

  • Type casting is used to convert variables from one type to another.

  • The casting operators (int) and (double) can be used to create a temporary value converted to a different data type.

  • Casting a double value to an int causes the digits to the right of the decimal point to be truncated.

  • Some programming code causes int values to be automatically cast (widened) to double values.

  • Values of type double can be rounded to the nearest integer by (int)(x + 0.5) or (int)(x – 0.5) for negative numbers.

  • Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.

  • If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. This could result in an incorrect value within the allowed range.

You have attempted of activities on this page
Next Section - 1.7. Unit 1 Summary