Skip to Content
Course content

9: Type Casting and Conversion

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Let's say we're building a small piece of software for a weather station. We've got raw data coming in from a sensor as a double because temperature isn't usually a whole number, but for our user-facing dashboard, we want to show a simplified, rounded-down integer value. I'll walk you through how I'd handle this, because the first time you try it, Java is going to give you some pushback.

The path of least resistance

First, I want to see if I can move data between types without any fuss. Let's try the opposite direction first: taking a whole number and putting it into a decimal type. I'll create an integer for a baseline temperature and assign it to a double.

int baselineTemp = 20;
double currentTemp = baselineTemp; 
System.out.println(currentTemp); // Output: 20.0

That worked instantly. No errors, no warnings. Java is happy because I'm moving a "small" type (int) into a "large" type (double). This is what we call widening. It's implicit; the compiler just does it for you because there's no risk of losing data. An integer fits perfectly inside a double.

Where the compiler slaps my wrist

Now, let's try the actual goal. I have a precise reading from my sensor, and I want to strip away the decimals to fit it into an integer variable for the dashboard.

double sensorReading = 22.75;
int dashboardTemp = sensorReading; // Error!

If you try to compile this, Java will throw a "possible lossy conversion" error. It's basically saying, "Hey, if I do this, I'm going to throw away .75, and I'm not authorized to just delete your data without a written request."

The compiler is being protective. Since a double can hold much more information than an int, this is narrowing. Java refuses to do this implicitly because it's a "dangerous" operation.

Forcing the issue

To fix this, I have to tell Java, "I know what I'm doing, just do it." We do this using a cast. I'll put the desired type in parentheses right before the value I'm converting.

double sensorReading = 22.75;
int dashboardTemp = (int) sensorReading; 
System.out.println(dashboardTemp); // Output: 22

Now it compiles. By adding (int), I've explicitly cast the double to an integer. I've effectively taken responsibility for the data loss.

The cost of forcing

Wait a second. Look at that output: 22. I didn't round to the nearest number; Java just chopped the decimal off entirely. This is called truncation.

If my sensor reading was 22.99, the result would still be 22. This is a critical detail. If you actually need to round the number rather than just truncate it, you can't rely on casting alone. You'd need something like Math.round(). But if you just need the whole number part, casting is the fastest way to get there.

I've seen developers get into trouble when they cast very large doubles into integers. If the double is larger than the maximum value an int can hold (about 2.1 billion), you won't get a compiler error, but you'll get a weird, wrapped-around number. Always be mindful of the scale of your data when you're forcing a narrowing conversion.




📋 Practical Task

The Pixel Coordinate Rounder

You are writing a graphics utility where object positions are calculated using double for smooth movement, but the screen can only render pixels at whole int coordinates.

Your Task:

  • Create a variable double objectX = 142.89; and double objectY = 310.12;.
  • Create two integer variables, pixelX and pixelY.
  • Use explicit casting to convert the double coordinates into the integer pixel variables.
  • Print the final coordinates in the format: "Rendering at: [pixelX], [pixelY]".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.