I’m trying to understand how to modify the elements of an array in Java. I have an array of integers, and I want to change the values of its elements. Here is my current code:
public class ModifyArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Original array:");
for (int number : numbers) {
System.out.print(number + " ");
}
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println("nModified array:");
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
Is this the correct way to modify array elements in Java? Are there any best practices or common pitfalls I should be aware of when working with arrays?
Thank you!
New contributor
Arulraj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2