Beginner Topic 5 of 54 Programming Fundamentals
Type Casting
Converting a value from one data type to another, explicitly or implicitly.
How it works
Type casting converts a value from one type to another. Explicit casts are written by the programmer, such as int("42") or (double) count, while implicit conversions, called coercion, are applied automatically by the language. Widening conversions like int to float are usually safe, whereas narrowing conversions can lose information, such as truncating the fractional part or wrapping around a smaller integer range.
Step-by-step walkthrough
- The input arrives as the string "42" and cannot be added to a number.
- An explicit cast int("42") parses the characters into a number.
- The result is the integer 42.
- Arithmetic now works and gives 43.
- Implicit casts happen silently, for example int + float becomes float.
Where it is used
Parsing user input strings into numbers, formatting numbers as text for display, widening integers to floats before division and converting between bytes and characters when reading files all rely on casting. Serialization and API boundaries are full of conversions.
Common pitfall
Implicit coercion can surprise: in JavaScript "5" + 1 is "51" but "5" - 1 is 4. Narrowing casts can silently overflow or truncate. Parsing can throw on malformed text. Always validate input before casting and prefer explicit conversions that document intent.
Where it fits in the course
Type Casting is topic 5 of 54 in Programming Fundamentals, rated Beginner. It follows Expressions. The next topic is Input and Output.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Type Casting?
Where do people use Type Casting?
What is the most common mistake with Type Casting?
What should I learn before this topic?
How can I practice it?
Is Type Casting hard to learn?
How long does it take to learn Type Casting?
Which topics are related to Type Casting?
What should I study after Type Casting?
Related topics
- Expressions (Programming Fundamentals)
- Input and Output (Programming Fundamentals)
- Operators (Programming Fundamentals)
- Conditional Statements (Programming Fundamentals)
- Type Inference (Languages & Compilers)
- Type Systems (Languages & Compilers)