ship
SalesForce Simplified

Your Go-To Resource for Streamlined Solutions and Expert Guidance

mountains
Empower Your Business
Dive deep into the world of CRM excellence, where innovation meets practicality, and transform your Salesforce experience with Forceshark's comprehensive resources

Apex Array Basics (Declaration, Initialization, Accessing Elements)

Alright, let’s start with the nuts and bolts. In Apex, arrays are actually just a special kind of list. Think of them as boxes where you can line up similar items - strings, numbers, objects - all in one neat row.

Declaring and Initializing Arrays

There are a couple of ways to create arrays (aka List in Apex). Here's how:

// Empty array of Strings
String[] names = new String[]{};
System.debug(names); // Outputs: ()

// Array with initial values
String[] fruits = new String[]{'Apple', 'Banana', 'Cherry'};
System.debug(fruits); // Outputs: (Apple, Banana, Cherry)

// Integer array with initial values
Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};
System.debug(numbers);

// Array with fixed size (elements default to null)
Integer[] fixedSizeArray = new Integer[4];
System.debug(fixedSizeArray); // Outputs: (null, null, null, null)

In Apex, you can use either the Type[] name syntax or the List<Type> name syntax. They’re interchangeable in most cases.

Accessing Elements

Once you've got data in your array, accessing it is a breeze. Just use the index, starting from zero:

System.debug(fruits[0]); // Apple
System.debug(fruits[2]); // Cherry

Need to update something?

fruits[1] = 'Blueberry';
System.debug(fruits); // (Apple, Blueberry, Cherry)

Just remember - if you try to access an index that doesn’t exist, Apex will throw an IndexOutOfBoundsException. Ouch.