Modify Elements
Lesson 11 of 16 in Coddy's Strings and Arrays in Java course.
To access elements in an array, refer to the element index number.
Just like in a string, indexes start at 0:
int[] numbers = {5, 9, 12};
int firstElement = numbers[0]; // Holds 5
int secondElement = numbers[1]; // Holds 9
int thirdElement = numbers[2]; // Holds 12Note that accessing indexes that do not exist will result in an error, for example -
numbers[3]
To change the value of a specific element in an array:
numbers[1] = 13;Now, the numbers array looks like this:
{5, 13, 12}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyWrite a function named printSome that gets an array of strings as an argument and prints the 1st and 3rd elements.
You can assume that the array will always be at least 3 elements long.
Try it yourself
class PrintSome {
public static void printSome(String[] arr) {
// Write code here
}
}