Please enable JavaScript to use CodeHS

Chapter 1

Primitive Types

1.6 Casting and Range of Variables

Casting allows you to change a variable’s type to better suit our needs.

How Casting Works

Let’s say you want to turn a double into an integer, or an integer into a double. To change a variable’s type you just add the type in between parentheses to cast it.

Consider the following:

int doubleToInt = (int)10.95;
// This will become '10'
Plain text

Casting an Integer to a Double

To cast an integer value to a double you add double in front of the variable.

int intVal = 10;

// Our 'doubleVal' variable is now '10.0'
double doubleVal = (double)intVal;
Plain text

Programs can also cast an int value to a double automatically since the value doesn’t change.

int intVal = 10;

// Our 'doubleVal' variable is now '10.0'
double doubleVal = intVal; // cast automatically
Plain text

Casting a Double to an Integer

To cast a double to an integer you add (int) in front of the variable. It is important to remember your new integer value will truncate the decimal.

double doubleVal = 7.6;

// Our 'intVal' variable is now '7'
int intVal = (int)doubleVal;
Plain text

Note that the change from casting is temporary. In the above example, intVal has a value of 7, but the value of doubleVal remains 7.6.

Truncating the value may not be the desired result. If you want to round the value, you can do this programmatically by adding half to the original value before truncating.

Rounding Using Casting

Division with Casting

If you divide two integers, even if you are setting them to a double, you will always be returned an integer.

int currResidents = 50;
int floorTotal = 56;

double average = floorTotal / currResidents;
// 'average' will return the value '1'
Plain text

We can get the correct answer by casting one of the variables to a double.

int currResidents = 50;
int floorTotal = 56;

double average = (double)floorTotal / currResidents;
// We now have the value of '1.12'
Plain text

Numerical Ranges

As you begin to explore numerical values in greater depth, it’s important to know about the existing range of variables. When you assign a value to a variable, you are actually associating that variable with binary data. Computers store all data in binary, and associate that variable with the binary data associated with the value that it has been assigned. int values are represented by 32 bits, or binary digits!

While that may seem like a lot, it actually does give you a finite limit to the numbers that you can store. Since ints are represented by 32 bits, the total possible combination of different values that can exist is 4,294,967,296. This range is split nearly evenly between negative and positive numbers, so you are able to store values from -2,147,483,648 to 2,147,483,647.

What happens if you go over the maximum or less than the minimum? If you go over or under the max and min, the value actually wraps around. This is called overflow. It’s important to note that overflow doesn’t always act as intended, and can create unexpected results. You will still get a value, but it may not be the value you expect.

Casting

Casting Order of Operations

Implicit Casting

Implicit casting (widening conversion)

A data type of lower size (occupying less memory) is assigned to a data type of higher size (more memory). This is done implicitly by the Java Virtual Machine, unlike the explicit casting we did in previous examples (so by the programmer). The lower size is widened to a higher size. This is also called automatic type conversion.

Example:

        int x = 10;                    // occupies 4 bytes
        double y = x;                  // occupies 8 bytes
        System.out.println(y);         // prints 10.0
Plain text

In the above code, the 4 bytes integer value is assigned to 8 bytes double value.

Min and Max Values of Integers

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.

We can print the maximum, minimum and bit-length of the integer primitive types. The maximum, minimum and bit-size of int are kept in built-in constants Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.SIZE.

The expected outputs are:

The minimium integer value in Java is -2147483648
The maximum integer value in Java is 2147483647
The total bit size for an integer in Java is 32
Plain text

This example will print the minimum, maximum and bit-length of of int primitive type.

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What will this java expression evaluate to?
    (int) 5.6

Exercise: Movie Ratings

Movies always come with ratings. A bad movie may have 1.4 stars, and a great movie may have 4.9 stars.

Your job is to write a program that asks the user for a movie rating as a double, and then rounds to the nearest int using the rounding with casting technique.

For example, a run of your program may look like this:

Enter movie rating (as a decimal)
1.4
Rating rounded: 1
Plain text

Another run may look like this:

Enter movie rating (as a decimal)
3.7
Rating rounded: 4
Plain text

If the initialized value has a decimal place of .5 or greater, you should round up:

Enter movie rating (as a decimal)
3.5
Rating rounded: 4
Plain text