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);
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
Not every String looks like a valid number — converting one that doesn't throws an exception immediately. 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
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.