Sub topic 1
How Apex handles types
Prerequisites
This chapter assumes you know basic programming ideas: variables, expressions, and conditionals. It also assumes you know at a high level what Salesforce objects and fields are. To run the examples, use the Developer Console's Execute Anonymous window in a Salesforce org or Developer Edition org.
Apex is strongly typed
Apex is a strongly typed language. Every variable, parameter, and return value has a declared type, and the compiler checks that type before the code runs. If you assign a value of the wrong type, you get a compile error instead of a surprise at run time.
You write the type before the variable name:
Integer count = 5;
String name = 'Acme';
Boolean isActive = true;
System.debug(name + ' ' + count + ' ' + isActive);Apex has no untyped var keyword for ordinary declarations. You always state the type yourself.
The families of types
Apex types fall into a few groups. Later chapters cover each group in detail.
- Primitive types: simple values such as
Integer,Long,Double,Decimal,String,Boolean,Date,Datetime,Time, andId. - Collections:
List,Set, andMap, which hold groups of values. - SObjects: types that represent Salesforce records, such as
AccountorContact. A genericSObjecttype can hold any of them. - Enums: a fixed set of named values that you define.
- Classes and interfaces: types you or Salesforce define, such as
Exceptionor your own classes.
The diagram shows how these groups relate.
Declaring types and checking them
The compiler checks each assignment. Some assignments are allowed because the conversion is safe. For example, an Integer fits into a Long, so this compiles:
Integer small = 7;
Long widened = small;
System.debug(widened);The reverse is not allowed without extra work, because a Long might not fit in an Integer. Conversions are covered in a later chapter.
Types and null
Every variable that does not hold a primitive value you gave it starts out as null. Here a String variable is declared but not assigned:
String note;
System.debug(note == null);This prints true. The type tells the compiler what the variable may hold, and null means it currently holds nothing. Calling a method on a null value causes a NullPointerException, so later chapters show how to guard against it.
Common mistakes
- Forgetting the type in a declaration.
count = 5;fails to compile ifcountwas never declared. - Assuming a variable has a useful default value. Uninitialized variables are
null, not0or an empty string. - Mixing types in an assignment without a conversion, such as assigning a
Stringto anInteger.
Exercise
Why does Apex reject Integer total = 'ten'; before the code runs?
Show answer
Apex is strongly typed and checks types at compile time. A String value cannot be assigned to an Integer variable, so the compiler reports an error.
Exercise
What value does String note; hold if you never assign to it, and what does note == null return?
Show answer
It holds null, so note == null returns true.