Menu
Coddy logo textTech

Modifying Arrays

Part of the Fundamentals section of Coddy's Java journey — lesson 60 of 73.

In addition to accessing the elements of an array, you can also modify them. To modify a specific element in an array, you can assign a new value to it using its index.

Here's an example:

String[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange";
System.out.println(my_array[0] + ", " + my_array[1] + ", " + my_array[2]);

Output:

apple, orange, cherry

banana was changed to an orange

challenge icon

Challenge

Easy

Create a method named <strong>changeElement</strong> that receives 3 arguments:

  • First argument is an array
  • Second argument is an index
  • Third argument is a new element

The method will return a modified array by changing the element in an index that is stored in the second argument with the value in the third argument.

For example with the following arguments: changeElement<strong>(</strong>new String[] {"1", "2", "3"}, 0, "9") the method will return [9, 2, 3]

Cheat sheet

To modify an array element, assign a new value using its index:

String[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange";  // Changes "banana" to "orange"

Try it yourself

import java.util.Scanner;

public class Main {
    public static String[] changeElement(String[] arr, int index, String newElement) {
        // Write code here
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String textArray = scanner.nextLine();
        int index = scanner.nextInt();
        scanner.nextLine();
        String newElement = scanner.nextLine();
        String[] arr = textArray.split(",");
        String[] modifiedArr = changeElement(arr, index, newElement);
        for (int i = 0; i < modifiedArr.length; i++) {
            System.out.print(modifiedArr[i] + " ");
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals