Accessing and Updating Array Elements in Java
Course: Core Java Training
Topic: Accessing and Updating Array Elements
Course Link: Core Java Training Course
Demo Link: Register for a Free Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Array Elements in Java
An array in Java is a data structure used to store multiple values of the same data type in a single variable. Each value stored in an array is called an element. Every element is identified by an index, which indicates its position in the array.
Java arrays use zero-based indexing, meaning the first element is located at index 0, the second at index 1, and so on. Accessing and updating array elements are fundamental operations used in programming tasks such as storing marks, processing sales figures, managing employee records, and performing calculations.
Example
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
}
}
Output:
10
30
In this example, numbers[0] accesses the first element, while numbers[2] accesses the third element.
2. Learning Objectives
- Understand array indexing and element positions.
- Access individual elements using square brackets.
- Update existing array values.
- Use loops to read and modify multiple elements.
- Understand array length and valid index ranges.
- Avoid common errors such as
ArrayIndexOutOfBoundsException.
- Apply array operations to practical programming problems.
3. Understanding Array Indexing
An index is the numeric position used to identify an element in an array. Java arrays begin at index zero, regardless of the number of elements they contain.
Example Array
int[] marks = {75, 82, 91, 68, 88};
| Index |
Element Value |
Description |
| 0 |
75 |
First element |
| 1 |
82 |
Second element |
| 2 |
91 |
Third element |
| 3 |
68 |
Fourth element |
| 4 |
88 |
Fifth element |
If an array contains n elements, its valid indexes range from 0 to n - 1. For an array with five elements, the valid indexes are 0 through 4.
4. Accessing Array Elements
To access an array element, write the array name followed by the required index inside square brackets. The expression returns the value stored at that position.
Syntax
arrayName[index]
Example: Accessing Individual Elements
public class AccessArray {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango", "Orange"};
System.out.println("First fruit: " + fruits[0]);
System.out.println("Second fruit: " + fruits[1]);
System.out.println("Last fruit: " + fruits[3]);
}
}
Output:
First fruit: Apple
Second fruit: Banana
Last fruit: Orange
The index determines which element is read. Accessing an element does not modify the array.
Accessing Elements Using Variables
An index can be stored in an integer variable. This is useful when the index is calculated dynamically or controlled by a loop.
int[] values = {100, 200, 300, 400};
int index = 2;
System.out.println(values[index]);
Output:
300
5. Updating Array Elements
Updating an array element means replacing the value currently stored at a particular index with a new value. Java allows an existing array element to be reassigned using the assignment operator (=).
Syntax
arrayName[index] = newValue;
Example: Updating an Integer Array
public class UpdateArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
numbers[1] = 99;
System.out.println(numbers[1]);
}
}
Output:
99
The original value at index 1 was 20. After the assignment, that element contains 99. The other elements remain unchanged.
Example: Updating Multiple Elements
public class MultipleUpdates {
public static void main(String[] args) {
int[] scores = {65, 70, 75, 80, 85};
scores[0] = 90;
scores[2] = 95;
scores[4] = 100;
for (int i = 0; i < scores.length; i++) {
System.out.println("Index " + i + ": " + scores[i]);
}
}
}
Output:
Index 0: 90
Index 1: 70
Index 2: 95
Index 3: 80
Index 4: 100
6. Accessing and Updating Elements Using Loops
Loops allow programmers to process array elements without writing a separate statement for every index. The standard for loop is especially useful when the index is required for reading or updating elements.
6.1 Accessing All Elements with a for Loop
public class DisplayArray {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
The loop begins at index 0 and continues while i is less than numbers.length. The condition ensures that only valid indexes are accessed.
6.2 Updating All Elements
You can update each array element by applying an operation to its current value.
public class IncreaseElements {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Output:
2 4 6 8 10
The first loop doubles every element. The second loop displays the updated values.
6.3 Updating Elements with a Condition
Sometimes only elements that satisfy a condition should be changed. For example, increase values below 50 by 10.
public class ConditionalUpdate {
public static void main(String[] args) {
int[] marks = {35, 55, 42, 70, 48};
for (int i = 0; i < marks.length; i++) {
if (marks[i] < 50) {
marks[i] += 10;
}
}
for (int mark : marks) {
System.out.print(mark + " ");
}
}
}
Output:
45 55 52 70 58
7. Accessing and Updating Elements with a while Loop
A while loop can also traverse an array. The programmer must initialize the index and update it during each iteration.
public class WhileArray {
public static void main(String[] args) {
int[] values = {10, 20, 30};
int i = 0;
while (i < values.length) {
values[i] = values[i] + 5;
System.out.println(values[i]);
i++;
}
}
}
Output:
15
25
35
If the index is not incremented, the loop may run indefinitely. Always verify that the loop condition eventually becomes false.
8. Using the Enhanced for Loop
The enhanced for loop, also called the for-each loop, provides a convenient way to read every element of an array without managing an index.
int[] numbers = {10, 20, 30};
for (int number : numbers) {
System.out.println(number);
}
However, assigning a new value to the loop variable does not update the corresponding primitive array element.
int[] numbers = {10, 20, 30};
for (int number : numbers) {
number = number * 2;
}
System.out.println(numbers[0]);
Output:
10
Here, number is a local variable that receives a copy of each primitive element. To update primitive array values, use an indexed loop such as for (int i = 0; i < numbers.length; i++).
9. Updating Arrays of Different Data Types
Java arrays can store primitive values or references to objects. The array's declared component type determines what values can be assigned to its elements.
9.1 Integer Array
int[] ages = {18, 21, 25};
ages[1] = 22;
9.2 Double Array
double[] prices = {99.5, 150.0, 250.75};
prices[0] = 89.99;
9.3 Character Array
char[] letters = {'A', 'B', 'C'};
letters[1] = 'Z';
9.4 String Array
String[] names = {"Amit", "Neha", "Ravi"};
names[0] = "Arjun";
For a reference-type array such as String[], an element stores a reference to an object. Reassigning the element changes the reference stored at that index; it does not modify the original string object.
10. Understanding the length Property
Every Java array has a built-in length field that returns the number of elements it can hold. It is a field, not a method, so use array.length, not array.length().
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length);
Output:
4
To access the final element, use index numbers.length - 1, provided the array is not empty.
int[] numbers = {10, 20, 30, 40};
int lastElement = numbers[numbers.length - 1];
System.out.println(lastElement);
Output:
40
11. Array Index Out of Bounds
Java throws ArrayIndexOutOfBoundsException when code attempts to access an array index outside the valid range. This can happen when the index is negative or greater than or equal to the array's length.
Incorrect Example
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);
This statement causes an exception because the valid indexes are 0, 1, and 2.
Correct Example
int[] numbers = {10, 20, 30};
int index = 2;
if (index >= 0 && index < numbers.length) {
System.out.println(numbers[index]);
} else {
System.out.println("Invalid array index");
}
Checking the index before accessing the array can prevent this common runtime error.
12. Difference Between Accessing and Updating
| Operation |
Purpose |
Example |
Effect |
| Accessing |
Reads a stored value |
int x = numbers[0]; |
Reads the element without changing it |
| Updating |
Replaces a stored value |
numbers[0] = 50; |
Changes the value at index 0 |
| Conditional update |
Changes a value when a condition is true |
if (numbers[i] < 10) numbers[i] = 10; |
Updates selected elements |
| Traversal |
Processes multiple elements |
for (int i = 0; i < numbers.length; i++) |
Visits elements one by one |
13. Practical Example: Updating Student Marks
Consider a program that stores student marks. If a student's mark is below 40, the program adds five bonus marks and then displays the updated results.
public class StudentMarks {
public static void main(String[] args) {
int[] marks = {35, 67, 38, 82, 29};
for (int i = 0; i < marks.length; i++) {
if (marks[i] < 40) {
marks[i] += 5;
}
}
System.out.println("Updated student marks:");
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + ": " + marks[i]);
}
}
}
Output:
Updated student marks:
Student 1: 40
Student 2: 67
Student 3: 43
Student 4: 82
Student 5: 34
This example demonstrates array traversal, conditional logic, compound assignment, and element updating.
14. Practical Example: Finding and Updating a Specific Value
In some applications, a program must locate a particular value and update it. The following example searches for the first occurrence of a target value and replaces it with a new value.
public class SearchAndUpdate {
public static void main(String[] args) {
int[] numbers = {12, 25, 37, 25, 49};
int target = 25;
int replacement = 100;
boolean updated = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
numbers[i] = replacement;
updated = true;
break;
}
}
if (updated) {
System.out.println("Element updated successfully.");
} else {
System.out.println("Target value not found.");
}
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
Output:
Element updated successfully.
12 100 37 25 49
The break statement stops the search after the first matching element is updated. Remove it if every occurrence of the target value should be replaced.
15. Common Mistakes and Troubleshooting
| Mistake |
Why It Happens |
Solution |
| Using index 1 for the first element |
Java indexing starts at zero |
Use index 0 for the first element |
| Accessing index equal to array length |
The last valid index is length minus one |
Use i < array.length in traversal loops |
| Forgetting to assign a new value |
An expression may calculate a result without storing it |
Use an assignment such as numbers[i] = numbers[i] + 1; |
Using length() for an array |
Confusing array length with String length |
Use array.length |
| Updating a for-each loop variable |
The variable holds a copy of a primitive element |
Use an indexed loop for primitive array updates |
| Using an incompatible value type |
The assigned value does not match the array component type |
Assign a compatible value or perform an appropriate conversion |
| Using an uninitialized array reference |
The array variable may contain null |
Initialize the array before accessing its elements |
16. Best Practices for Working with Array Elements
- Use meaningful array and index variable names.
- Use
array.length to make loop boundaries adapt to the array size.
- Check index values when they come from user input or calculations.
- Use indexed loops when you need to update primitive elements.
- Keep array traversal and modification logic easy to understand.
- Avoid changing array elements unexpectedly inside unrelated methods.
- Test empty arrays and single-element arrays where appropriate.
- Remember that arrays have a fixed length after creation, even though their elements can be updated.
- Use an appropriate collection, such as
ArrayList, when the number of elements needs to grow or shrink dynamically.
17. Practice Exercises
- Basic Access: Create an integer array containing five numbers and print the first, third, and last elements.
- Single Update: Create an array of six values and replace the element at index 3 with 500.
- Update All: Write a program that multiplies every element of an integer array by three.
- Conditional Update: Increase every negative number in an array by 10.
- Search and Replace: Search for a target number and replace every occurrence with another number.
- Student Marks: Store marks for five students, add five marks to each score below 40, and print the updated array.
- Reverse Display: Display array elements from the last index to the first without changing their stored order.
- Input Validation: Read an index and a replacement value from the user. Update the array only when the index is valid.
18. Mini Project: Inventory Quantity Updater
Objective: Create a simple inventory program that stores quantities of five products, updates one product's quantity, and displays the final inventory.
Requirements
- Create an integer array containing five product quantities.
- Choose a valid product index to update.
- Replace the quantity at that index with a new value.
- Display all updated quantities using a loop.
- Handle invalid indexes without accessing the array.
Sample Implementation
public class InventoryUpdater {
public static void main(String[] args) {
int[] quantities = {12, 8, 20, 15, 6};
int productIndex = 2;
int newQuantity = 25;
if (productIndex >= 0 && productIndex < quantities.length) {
quantities[productIndex] = newQuantity;
System.out.println("Quantity updated.");
} else {
System.out.println("Invalid product index.");
}
for (int i = 0; i < quantities.length; i++) {
System.out.println(
"Product " + (i + 1) + ": " + quantities[i]
);
}
}
}
Expected Result: The quantity at index 2 changes from 20 to 25, while all other product quantities remain unchanged.
19. Interview Questions and Answers
Q1. What is an array element in Java?
An array element is an individual value stored at a specific index within an array.
Q2. How do you access an array element?
Use the array name followed by an index in square brackets, such as numbers[2].
Q3. How do you update an array element?
Assign a new value to a valid index, for example, numbers[2] = 50;.
Q4. Why does Java use zero-based indexing?
Array indexing in Java follows a zero-based convention, where the first element is at index zero. Programmers must account for this when calculating positions.
Q5. What is the last valid index of an array?
For a non-empty array, the last valid index is array.length - 1.
Q6. What happens when an invalid index is accessed?
Java throws an ArrayIndexOutOfBoundsException when the index is outside the valid range.
Q7. Can an array's length change when an element is updated?
No. An array's length is fixed when the array is created. Updating an element changes its value, not the array's length.
Q8. Can a for-each loop update primitive array elements directly?
No. The loop variable receives a copy of each primitive value. Use an indexed loop to assign values to the original array elements.
Q9. What is the difference between reading and writing an array element?
Reading retrieves the value at an index. Writing assigns a new value to the element at that index.
Q10. How can you safely traverse an array?
Use an index that starts at zero and continues while it is less than array.length. This keeps each index within the valid range.
20. Quick Revision Checklist
- An array stores multiple values of one declared component type.
- Array indexes start at zero.
- Read an element with
array[index].
- Update an element with
array[index] = newValue;.
- Use
array.length to find the number of elements.
- The last valid index is
array.length - 1, if the array is not empty.
- Use indexed loops to update multiple primitive elements.
- Validate indexes to avoid
ArrayIndexOutOfBoundsException.
- Updating an element does not change the array's length.
21. Conclusion
Accessing and updating array elements are essential Core Java skills. By understanding zero-based indexing, using square-bracket notation, applying assignment operators, and traversing arrays with loops, programmers can efficiently manage groups of related values. Careful index validation and consistent use of array.length help prevent common runtime errors. Practicing these techniques with student marks, inventory quantities, and search-and-update programs builds a strong foundation for more advanced Java programming.
To continue learning, explore the JustAcademy Core Java Training Course, register for a demo, or visit the JustAcademy homepage.