Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
9: Type Casting and Conversion
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;anddouble objectY = 310.12;. - Create two integer variables,
pixelXandpixelY. - Use explicit casting to convert the double coordinates into the integer pixel variables.
- Print the final coordinates in the format:
"Rendering at: [pixelX], [pixelY]".
There are no comments for now.