Type Casting Fundamentals
What you'll learn: How to safely convert a value from one data type to another in your programs.
What is Type Casting?
Type casting is the process of converting a value from one data type to another. Think of it like translating measurements: converting inches to centimeters doesn't change the actual distance, just how you express it. Similarly, casting 5 from an integer to a floating-point number gives you 5.0 — same value, different representation.
Two Flavors of Casting
Implicit casting (also called automatic conversion) happens when the compiler safely converts a value for you. For example, storing an integer in a floating-point variable usually works automatically because no information is lost:
int wholeNumber = 42;
float decimalNumber = wholeNumber; // becomes 42.0 automatically
Explicit casting is when you tell the compiler to convert, even if it might lose information. You need this when going from "bigger" to "smaller" types:
float pi = 3.14;
int rounded = (int)pi; // you explicitly cast, result is 3 (decimal lost!)
Why It Matters
Different data types have different capabilities and memory sizes. An integer can't hold decimal points, and a character can't store a word. Type casting lets you move data between these worlds, but you must understand what you might lose in translation — like how casting 3.99 to an integer truncates it to 3, not rounds to 4.
Key Takeaway: Type casting converts values between data types, either automatically (implicit) when safe, or manually (explicit) when you accept potential data loss.