Search Here

Apex - Arrays program

 1. Creating an Array (List):


You can create an array (list) to store elements of the same data type.


List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};


2. Accessing Elements in an Array:


You can access elements in an array using square brackets and an index (0-based).


List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};

String firstFruit = fruits[0]; // Access the first element

System.debug(firstFruit); // Outputs: Apple


3. Modifying Elements in an Array:


You can modify elements in an array by assigning new values to specific indices.


List<String> colors = new List<String>{'Red', 'Blue', 'Green'};

colors[1] = 'Yellow'; // Change the second element to Yellow

System.debug(colors); // Outputs: (Red, Yellow, Green)


4. Finding the Length of an Array:


You can determine the number of elements in an array using the size() method.


List<Integer> scores = new List<Integer>{80, 95, 70, 88};

Integer numberOfScores = scores.size();

System.debug('Number of scores: ' + numberOfScores); // Outputs: Number of scores: 4


5. Iterating Over an Array:


You can use a for loop to iterate over the elements in an array.


List<String> weekdays = new List<String>{'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'};

for (String day : weekdays) {

    System.debug(day);

}


6. Adding and Removing Elements:

You can add elements to the end of an array using the add() method and remove elements using the remove() method.


List<String> animals = new List<String>{'Cat', 'Dog'};

animals.add('Elephant'); // Add an element

animals.remove(1); // Remove the second element (Dog)

System.debug(animals); // Outputs: (Cat, Elephant)






Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.