Sub topic 1
How Apex Handles Types
Prerequisites
Assume you know variables, expressions, and conditionals. You should also recognize Salesforce objects and fields, and have access to an org or Developer Console.
How Apex Handles Types
Apex is strongly typed. Every variable has a declared type, and the compiler checks whether assigned values and operations are valid. A type describes what a value represents and which operations it supports.
Apex types include primitive values, collections, Salesforce records called SObjects, and enums. This chapter focuses on common primitive types and variables.
Primitive Data Types at a Glance
| Type | Typical use |
|---|---|
| `Integer` | Whole numbers within the integer range |
| `Long` | Larger whole numbers |
| `Double` | Approximate decimal calculations |
| `Decimal` | Exact decimal values, such as currency |
| `String` | Text |
| `Boolean` | `true` or `false` |
| `Date`, `Datetime`, `Time` | Date and time values |
| `Id` | Salesforce record identifiers |
Declaring and Initializing Variables
A declaration gives a variable a type and name. Initialization gives it a starting value.
Integer count = 5;
Decimal price = 19.99;
String name = 'Acme';
Boolean active = true;
Date today = Date.newInstance(2026, 11, 30);
System.debug(name + ' ' + count);A local variable is visible only within the block where it is declared. Declare a variable before using it, and choose a type that matches the value's meaning.
Working with Null
null means that a variable has no value. An uninitialized reference-like variable can contain null.
String note;
Integer total = null;
System.debug(note == null);
System.debug(total == null);Check for null before calling methods or accessing values. Otherwise, Apex can raise a null reference error.
Integer, Long, Double, and Decimal
Use Integer for ordinary whole numbers and Long for larger whole numbers. Use Double for approximate scientific or measurement values. Use Decimal when exact decimal arithmetic matters, especially for money.
Decimal total = 10.00;
Decimal rate = 0.075;
Decimal tax = (total * rate).setScale(2, RoundingMode.HALF_UP);
System.debug(tax);A smaller numeric type can widen automatically to a larger compatible type, such as Integer to Long.
Strings
A String stores text in single quotes. In Apex, == compares strings without considering letter case, while equals is case-sensitive.
String a = 'apex';
String b = 'APEX';
System.debug(a == b); // true
System.debug(a.equals(b)); // falseExercise
Which type should you choose for a currency amount, and why?
Show answer
Choose Decimal because it represents decimal values exactly and supports controlled rounding.