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, cherrybanana was changed to an orange
Challenge
EasyCreate 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] + " ");
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 411Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed Array3Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else