Beginner 20 min read

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);
  1. String priceText = '19.99'; — a number, stored as text.
  2. Decimal price = Decimal.valueOf(priceText); — Decimal.valueOf() converts the text into a real Decimal value.
  3. (blank line)
  4. Integer count = 5; — a real number.
  5. String countText = String.valueOf(count); — converts it the other way, Integer to String.

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
  1. String badInput = 'not a number'; — text that doesn't actually look like a number.
  2. Decimal price = Decimal.valueOf(badInput); — Apex tries to parse it as a Decimal and 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)

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Type Conversion vs Casting Quiz

1. What happens if you try to convert a non-numeric String to a Decimal?

Log in to submit the quiz and save your score.

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.