Tino Intro To Java

Last modified: January 07, 2023

Typecasting

Typecasting is the technique of converting one data type into another.

Typecasting primitive data

If you have a decimal value (i.e. a stored in a double) and you try to store it in an int, the Java compiler will complain that you may lose data. To store a decimal in an int, it would need to truncate (chop off) the decimal.

For example, 5.8 stored as an int would be 5. You can tell the compiler to typecast a primitive and accept any loss of data:

Syntax: (new_type)(expression)

double d = 3.796;
int n = (int)(d * 10 + 5); // n is now 42

// Math.random() returns a double from 0 inclusive to 1 exclusive
double x =       Math.random()*10 ;  // Returns 0.0 - 9.9999999
int x = (int)(Math.random()*10);  // Returns 0 - 9

Typecasting non-primitive objects

Typecasting can be applied to data beyond primitives.

In Greenfoot, this is especially useful for typecasting the World object.

When you make a subclass of World, it inherits all the methods from the World class. You can call getWorld() on an Actor and it will return the World object that Actor is in. You can then call any methods on that world that the World class has.

public class Ball {
    public void act() {
        World w = getWorld();
        int worldHeight = w.getHeight();
    }
}

But what if you have a subclass of World named GameWorld that has custom a method like isGameOver()? In that case, the compiler would need to be told that the world is a GameWorld. You can do that with typecasting like this:

GameWorld gw = (GameWorld) getWorld();
if (gw.isGameOver()) {
    // do what you do when game is over
}

Dark Mode

Outline