Apex Language Basics and Data Types
Apex is a strongly-typed, object-oriented programming language developed by Salesforce that runs on the Force.com platform. Understanding its language basics and data types is fundamental for the Platform Developer I certification. **Primitive Data Types:** - **Integer**: 32-bit whole numbers (e.g… Apex is a strongly-typed, object-oriented programming language developed by Salesforce that runs on the Force.com platform. Understanding its language basics and data types is fundamental for the Platform Developer I certification. **Primitive Data Types:** - **Integer**: 32-bit whole numbers (e.g., Integer count = 10;) - **Long**: 64-bit whole numbers for larger values - **Double**: 64-bit floating-point numbers for decimals - **Decimal**: Numbers with decimal points, commonly used for currency calculations with precision - **String**: Text values enclosed in single quotes (e.g., String name = 'Salesforce';) - **Boolean**: True, false, or null values - **Date**: Stores date without time - **DateTime**: Stores both date and time - **Time**: Stores time only - **ID**: 18-character Salesforce record identifier - **Blob**: Binary data type for attachments **Collections:** - **List**: Ordered collection of elements allowing duplicates (e.g., List<String> names = new List<String>();) - **Set**: Unordered collection of unique elements - **Map**: Key-value pairs where keys are unique (e.g., Map<Id, Account> accountMap) **sObjects:** These represent Salesforce objects like Account, Contact, or custom objects. Example: Account acc = new Account(Name='Test'); **Key Language Basics:** - Variables must be declared with their data type before use - Apex is case-insensitive - Statements end with semicolons - Null is a valid value for all data types - Type casting can be implicit or explicit - Constants are declared using the 'final' keyword - Enums define a fixed set of constants **Governor Limits Awareness:** Apex runs in a multi-tenant environment, so understanding data types helps optimize SOQL queries, heap size, and CPU time. Using appropriate collections like Maps instead of nested loops is essential for writing efficient, bulkified code that respects platform limits. Mastering these fundamentals is critical for building robust automation solutions on the Salesforce platform.
Apex Language Basics & Data Types – Complete Guide for Salesforce Platform Developer 1
Why Apex Language Basics and Data Types Matter
Apex is the strongly-typed, object-oriented programming language at the heart of the Salesforce platform. Understanding its language basics and data types is foundational for every Salesforce Platform Developer 1 exam candidate because virtually every other topic—triggers, classes, SOQL, DML, governor limits—depends on your ability to correctly declare variables, choose appropriate data types, and write syntactically valid Apex code. The exam regularly tests whether you can identify correct declarations, understand type compatibility, and predict runtime behavior based on data type rules.
What Are Apex Language Basics?
Apex language basics encompass the fundamental syntax, structure, and constructs you need to write Apex code. Key areas include:
• Variables and Constants – Declaring variables with explicit data types, using the final keyword for constants.
• Operators – Arithmetic (+, -, *, /), comparison (==, !=, <, >, <=, >=), logical (&&, ||, !), and the ternary operator (?:).
• Control Flow Statements – if/else, switch on, for loops, while loops, do-while loops, and for-each (iteration) loops.
• Comments – Single-line (//) and multi-line (/* */) comments.
• Case Sensitivity – Apex is case-insensitive for keywords and identifiers, but string comparisons are case-sensitive by default unless you use methods like equalsIgnoreCase().
• Statement Termination – Every statement must end with a semicolon (;).
• Null Handling – Variables that are not initialized default to null (for object types) or to a type-specific default (0 for Integer, false for Boolean).
What Are the Apex Data Types?
Apex is strongly typed, meaning every variable must be declared with a specific data type. The major categories are:
1. Primitive Data Types
• Integer – A 32-bit whole number (no decimal). Example: Integer count = 10;
• Long – A 64-bit whole number for larger values. Example: Long bigNum = 2147483648L;
• Double – A 64-bit floating-point number. Example: Double price = 19.99;
• Decimal – An arbitrary-precision signed number commonly used for currency and financial calculations to avoid floating-point rounding. Example: Decimal amount = 100.50;
• String – A sequence of characters enclosed in single quotes. Example: String name = 'Salesforce'; Note: Apex uses single quotes, not double quotes.
• Boolean – true, false, or null. Example: Boolean isActive = true;
• Date – A date without time. Example: Date today = Date.today();
• Datetime – A date with time. Example: Datetime now = Datetime.now();
• Time – A time without date. Example: Time t = Time.newInstance(14, 30, 0, 0);
• Blob – Binary data, often used for attachments or cryptographic operations.
• ID – A special 18-character Salesforce record identifier. Apex automatically converts 15-character IDs to 18-character IDs. Example: Id accountId = '001XXXXXXXXXXXX';
2. sObject Types
• Generic: sObject can hold any Salesforce record.
• Specific: Account, Contact, Opportunity, custom objects like Invoice__c.
• You can cast a generic sObject to a specific type: Account acc = (Account)mySObject;
3. Collections
• List – An ordered collection that allows duplicates. Example: List<String> names = new List<String>(); Also supports array notation: String[] names = new String[]{};
• Set – An unordered collection of unique elements. Example: Set<Id> idSet = new Set<Id>();
• Map – A collection of key-value pairs where keys are unique. Example: Map<Id, Account> accMap = new Map<Id, Account>();
4. Enums
• User-defined or system enums. Example: public enum Season { WINTER, SPRING, SUMMER, FALL }
• System enums include DisplayType, SoapType, and others.
5. The Object Type
• The generic Object type can hold any value. You must cast it to a specific type before using type-specific methods.
How Data Types Work in Practice
Variable Declaration and Initialization:
Integer x = 5; – Declares and initializes in one step.
String s; – Declares s; its value is null until assigned.
Type Casting:
• Implicit (widening): Integer to Long or Double happens automatically.
• Explicit (narrowing): You must cast, e.g., Integer i = (Integer)myDouble; but note this is not always safe.
• sObject casting: Account a = (Account)genericSObject;
Null Safety:
Calling a method on a null reference throws a NullPointerException. Always check for null when dealing with variables that may not be initialized or with query results that may return empty lists.
String Behavior:
• Strings are immutable in Apex.
• Concatenation uses the + operator.
• Single quotes are used: 'Hello' not "Hello".
• Escape characters: \' for a literal single quote, \n for newline.
Decimal vs. Double:
Use Decimal for currency fields and precise calculations. Double can introduce floating-point precision errors. Salesforce currency fields map to Decimal in Apex.
ID Type Specifics:
• Assigning a String to an ID variable performs a runtime validation; an invalid ID format throws a StringException.
• ID comparisons are case-insensitive.
Collections Deep Dive
Lists:
• Access elements by index (0-based): names[0] or names.get(0)
• Common methods: add(), size(), isEmpty(), contains(), remove(), sort()
• Can be initialized from SOQL: List<Account> accs = [SELECT Id, Name FROM Account];
Sets:
• Automatically prevent duplicates.
• Useful for filtering and checking membership: mySet.contains(value)
• Cannot access by index.
Maps:
• Common pattern: Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, Name FROM Account]); This constructor auto-populates keys with record IDs.
• Methods: put(), get(), containsKey(), keySet(), values(), size()
Constants and the Final Keyword
• Use final to declare a constant: final Integer MAX_SIZE = 100;
• Once assigned, a final variable cannot be reassigned.
• Static final variables in a class act as class-level constants.
Common Pitfalls Tested on the Exam
1. Using double quotes for Strings – Apex requires single quotes. Double quotes cause a compile error.
2. Confusing == with .equals() – For strings, == and .equals() behave the same in Apex (both compare values, not references), but for sObjects, == compares all field values while === (not available in Apex) is not used.
3. NullPointerException – Accessing methods or properties on a null variable. The exam may ask what happens when you call .size() on a null list.
4. Integer division – Dividing two Integers gives an Integer result (truncated, not rounded). Example: 7/2 = 3, not 3.5.
5. Initialization of primitives – Integer defaults to null (not 0) when declared but not initialized. Boolean defaults to null. Only local primitives in some contexts are null by default.
6. List vs. Array syntax – Both List<String> and String[] are valid and equivalent.
Exam Tips: Answering Questions on Apex Language Basics and Data Types
Tip 1: Read Declarations Carefully
Many questions hinge on whether a variable is declared with the correct type. Check that the left-hand type matches what is being assigned on the right. For example, assigning a List to a Set variable will not compile.
Tip 2: Know Default Values
Uninitialized object-type variables (including String, sObject, collections) are null. Calling methods on them causes a NullPointerException. The exam loves to test this with scenarios like: List<String> myList; myList.add('test'); — this throws a NullPointerException because myList is null.
Tip 3: Distinguish Decimal from Double
When a question involves currency calculations or precise arithmetic, the correct data type is almost always Decimal. If the question uses a currency field from an sObject, it maps to Decimal.
Tip 4: Remember Single Quotes
If you see a code snippet using double quotes for a String literal, that code will not compile. This is a quick elimination technique for wrong answers.
Tip 5: Understand Collection Constructors
A Map<Id, sObject> can be constructed directly from a SOQL query. A Set cannot be constructed directly from SOQL; you would typically use a Map's keySet() or iterate a list.
Tip 6: Watch for Integer Arithmetic
If both operands are Integer, the result is Integer. To get a Decimal or Double result, at least one operand must be Decimal or Double. Example: Decimal result = 7.0 / 2; gives 3.5, but Decimal result = 7 / 2; gives 3 (Integer division happens first).
Tip 7: ID Type Validation
Assigning an invalid String to an Id variable causes a runtime exception, not a compile-time error. The exam may test whether you know this is caught at runtime.
Tip 8: Apex Is Case-Insensitive for Identifiers
Integer myVar = 5; and integer MYVAR = 5; are the same variable. However, string comparisons are case-sensitive by default. Know the difference between String methods like equals() (case-sensitive) and equalsIgnoreCase().
Tip 9: Know the Switch Statement Syntax
Apex uses switch on (not just switch). The when keyword replaces case. There is no fall-through; no break statement is needed. Example:
switch on myVar { when 1 { // do something } when 2 { // do something else } when else { // default } }
Tip 10: Eliminate Answers That Mix Syntax from Other Languages
Apex looks similar to Java but is not identical. If you see syntax like System.out.println(), var keyword, int (lowercase), or double-quoted strings, those are typically wrong. Apex uses System.debug(), explicitly typed variables (Integer, not int), and single-quoted strings.
Tip 11: Practice With Tricky Null Scenarios
Boolean b; if (b) { ... } — This throws an exception because b is null, not false. The exam may present code that assumes uninitialized Booleans are false.
Tip 12: Understand Type Compatibility in Collections
A List<Account> can be assigned to a List<sObject> variable (covariance in Apex). However, you cannot add a Contact to a list that was originally instantiated as List<Account> even if the variable type is List<sObject>. This nuance appears in advanced questions.
Summary
Mastering Apex language basics and data types is non-negotiable for the Platform Developer 1 exam. Focus on primitive types and their defaults, collection types and their constructors, null handling, type casting, and common syntax rules. When facing exam questions, always read the code carefully for type mismatches, null references, and syntax errors. Apply the elimination strategy—rule out answers with invalid syntax first, then analyze the remaining options for runtime behavior. With a solid understanding of these fundamentals, you will be well-prepared for both the exam and real-world Salesforce development.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!