Type Conversion vs Casting
By the end of this lesson, you'll be able to:
- Convert between compatible types using built-in methods
- Explain the difference between conversion and casting
- Handle a conversion that might fail
Prerequisites: "Logical Operators"
Converting between types
String priceText = '19.99';
Decimal price = Decimal.valueOf(priceText);
Integer count = 5;
String countText = String.valueOf(count);
String priceText = '19.99';— a number, stored as text.Decimal price = Decimal.valueOf(priceText);—Decimal.valueOf()converts the text into a realDecimalvalue.- (blank line)
Integer count = 5;— a real number.String countText = String.valueOf(count);— converts it the other way,IntegertoString.
Most primitive types provide a valueOf() method for exactly this — turning a compatible value from one type into another.
When conversion can fail
String badInput = 'not a number';
Decimal price = Decimal.valueOf(badInput); // throws a runtime exception
String badInput = 'not a number';— text that doesn't actually look like a number.Decimal price = Decimal.valueOf(badInput);— Apex tries to parse it as aDecimaland fails immediately.
Warning: converting a String that isn't validly formatted for the target type throws a runtime exception on the spot — this line never returns a fallback value like null or 0. Real code that converts user-entered text should expect this and handle it (Module "Apex Language Essentials" covers exception handling properly).
Casting: a different concept entirely
Casting comes up once you reach more general types like Object (Module "Enterprise Apex Architecture" territory) — it tells Apex "trust me, I know this Object is really a String underneath," rather than converting one kind of value into another. It's a preview, not something you need to use yet — the important thing now is not confusing it with conversion.
Exercise
Declare a String called quantityText holding '25'. Convert it to an Integer called quantity using Integer.valueOf(). Debug the result.
Show hint
Integer.valueOf(quantityText)
Type Conversion vs Casting Quiz
Leaderboard
- 1. Monde Masiza 1/1
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Type conversion turns a value of one type into an equivalent value of another (like turning the String '42' into the Integer 42). Casting is Apex's term for treating a more general type as a more specific one it already actually is underneath.