Sub topic 13
Converting and casting between types
This chapter assumes you can declare variables and know the primitive types from earlier chapters: Integer, Long, Double, Decimal, String, Boolean, Date, and Datetime. It also assumes you know what an SObject is. Apex is strongly typed, so every conversion between types either happens implicitly, is requested with a cast, or is performed by a method such as valueOf. Knowing which of the three applies prevents most compile errors and runtime exceptions in this area.
The three kinds of conversion
| Kind | Syntax | When it happens | Failure mode |
|---|---|---|---|
| Implicit widening | `Long l = someInteger;` | The compiler sees a safe, lossless conversion | None |
| Explicit cast | `(String) obj` | You narrow a general type to a specific one | `System.TypeException` at runtime |
| Conversion method | `Integer.valueOf('42')` | You convert between unrelated types such as String and Integer | Exception if the value cannot be parsed |
Implicit widening
Apex converts a narrower numeric type to a wider one automatically. The order is Integer, Long, Double, Decimal. You can assign an Integer to a Long, a Long to a Decimal, and so on, with no cast.
Integer small = 7;
Long widened = small;
Decimal asDecimal = widened;
Double asDouble = small;
System.debug(widened + ' ' + asDecimal + ' ' + asDouble);The reverse direction is not implicit. This line does not compile:
Decimal d = 3.7;
Integer i = d; // Compile error: Illegal assignment from Decimal to IntegerTo go the other way, call an explicit method such as d.intValue(), which truncates, or Integer.valueOf(d). Choose deliberately, because the two behave differently for fractions, as shown later in this chapter.
Implicit conversion also applies to the + operator with a String. When one operand is a String, Apex converts the other operand to a String and concatenates.
Integer count = 5;
String message = 'Count: ' + count;
System.debug(message);Explicit casting
A cast is a type name in parentheses before an expression. You need one when a variable has a general type, such as Object or the generic SObject, and you want to use it as a more specific type.
Object value = 'text';
String asString = (String) value;
System.debug(asString.toUpperCase());A cast does not convert data. It tells the runtime to treat the same value as a different type. If the value is not actually that type, the cast fails at runtime.
Object value = 42;
try {
String s = (String) value;
} catch (System.TypeException e) {
System.debug('Cast failed: ' + e.getMessage());
}The compiler cannot catch this problem, because value is declared as Object. To check first, use instanceof.
Object value = 42;
if (value instanceof Integer) {
Integer n = (Integer) value;
System.debug(n + 1);
} else if (value instanceof String) {
System.debug('It is a String');
}Casting with collections of Object
Collections are common sources of casts. A List<Object> holds anything, and each element needs a cast when you read it.
List<Object> mixed = new List<Object>{ 1, 'two', 3.5 };
for (Object item : mixed) {
if (item instanceof Integer) {
System.debug('Integer: ' + (Integer) item);
} else if (item instanceof String) {
System.debug('String: ' + (String) item);
} else {
System.debug('Other: ' + item);
}
}Note that 3.5 is a Decimal literal in Apex, so it reaches the else branch here.
Conversion methods: valueOf and friends
Most primitive types provide a static valueOf method that parses a String or converts from another type. The related parse methods exist on some types for locale-aware input.
Integer parsed = Integer.valueOf('42');
Decimal price = Decimal.valueOf('19.99');
Boolean flag = Boolean.valueOf('true');
Date d = Date.valueOf('2026-11-30');
Datetime dt = Datetime.valueOf('2026-11-30 12:00:00');
System.debug(parsed + ' ' + price + ' ' + flag + ' ' + d + ' ' + dt);A String that does not match the expected format throws an exception. Integer.valueOf('abc') throws System.TypeException. Handle user-supplied text with a try-catch, or validate it first.
String input = 'abc';
Integer result;
try {
result = Integer.valueOf(input);
} catch (System.TypeException e) {
result = 0;
}
System.debug(result);Converting any value to a String is usually done with String.valueOf, which accepts null and returns null rather than throwing.
Integer n = 100;
Decimal missing = null;
System.debug(String.valueOf(n));
System.debug(String.valueOf(missing));Truncation versus rounding
Narrowing a Decimal or Double to an Integer behaves differently depending on the method.
Decimal d = 3.7;
System.debug(d.intValue()); // 3, truncates
System.debug(Integer.valueOf(d)); // 3, truncates
System.debug(d.round()); // 4, returns a Long, rounded
System.debug(d.setScale(0, RoundingMode.HALF_UP)); // 4, still a DecimalUse setScale with an explicit RoundingMode whenever the rounding rule matters, such as for money.
Overflow when narrowing
Narrowing a Long to an Integer can lose data. Integer.valueOf(Long) is not available in every form, so check the method signature for your API version. A safe approach is to range-check the value yourself.
Long big = 8000000000L;
if (big <= 2147483647L && big >= -2147483648L) {
Integer safe = (Integer) big;
System.debug(safe);
} else {
System.debug('Value does not fit in an Integer');
}Id and String
An Id is a special type that holds a 15- or 18-character record identifier. You can assign a valid String to an Id, and an Id to a String, without a cast. Apex validates the String when it is assigned to an Id.
String raw = '001000000000001AAA';
Id recordId = raw;
String back = recordId;
System.debug(recordId.getSObjectType());
System.debug(back);An invalid String throws System.StringException at assignment. The Id also tells you which SObject type it belongs to, through getSObjectType().
SObject casts
A generic SObject variable can hold any record. To read type-specific fields, cast it to the concrete type.
SObject generic = new Account(Name = 'Acme');
Account acc = (Account) generic;
System.debug(acc.Name);Casting to the wrong concrete type throws a System.TypeException. Casting in the other direction needs no cast: any concrete SObject can be assigned to a variable of type SObject.
Contact c = new Contact(LastName = 'Smith');
SObject generic = c;
System.debug(generic.get('LastName'));Generic access with get and put returns or accepts Object, so you cast the result of get when you need a typed value.
Account acc = new Account(Name = 'Acme', NumberOfEmployees = 50);
Integer employees = (Integer) acc.get('NumberOfEmployees');
System.debug(employees);Collection conversions
Collections are not interchangeable simply because their element types are related. A List<Account> can be assigned to a List<SObject>, because Apex permits this for SObject lists. A List<Integer> cannot be assigned to a List<Long>.
List<Account> accounts = new List<Account>{ new Account(Name = 'A') };
List<SObject> records = accounts;
System.debug(records.size());To convert between other collection types, build a new collection. A Set from a List removes duplicates, and a List from a Set gives an indexable copy.
List<String> names = new List<String>{ 'a', 'b', 'a' };
Set<String> unique = new Set<String>(names);
List<String> back = new List<String>(unique);
System.debug(unique.size() + ' ' + back.size());Common errors
- Assigning a Decimal or Double to an Integer without a method. This fails at compile time.
- Casting an
Objectwithout checkinginstanceof. This fails at runtime withTypeException. - Passing unvalidated text to
Integer.valueOforDate.valueOf. This throws on bad input. - Expecting
intValue()to round. It truncates. - Assuming
Integer.valueOfon a null String returns null. Test for null before parsing.
Exercise
What do d.intValue() and d.setScale(0, RoundingMode.HALF_UP) return when Decimal d = 2.6;, and why do they differ?
Show answer
intValue() returns the Integer 2 because it truncates the fractional part. setScale(0, RoundingMode.HALF_UP) returns the Decimal 3 because it rounds halves and above upward. Use setScale with a rounding mode when the rounding rule matters.
Exercise
Given Object value = 42;, what happens when you run String s = (String) value;, and how can you avoid it?
Show answer
The code compiles, but at runtime it throws System.TypeException because the value is an Integer, not a String. Check the type first with if (value instanceof String) before casting, or use String.valueOf(value) if you want a String representation of any value.