Array Operations in Java
Array Operations in Java
Arrays are a fundamental data structure in Java that allow storing multiple elements of the same
type in a contiguous memory location. The basic operations that can be performed on arrays
include insertion, accessing elements, updating elements, and deletion.
Insertion refers to the process of adding elements into an array. Since arrays in Java have a fixed
size, direct insertion is only possible at initialization or by modifying an existing index. If
dynamic insertion is needed, an array must be resized (which is why ArrayList is often
preferred for dynamic arrays).
Methods of Insertion:
1. At Initialization:
2. int[] numbers = {10, 20, 30, 40, 50}; // Inserting values at
initialization
3. Using Index Assignment:
4. int[] numbers = new int[5];
5. numbers[0] = 10; // Inserting elements at specific indices
6. numbers[1] = 20;
7. Expanding an Array: (Not directly possible, but can be done using Arrays.copyOf())
8. int[] oldArray = {1, 2, 3};
9. int[] newArray = Arrays.copyOf(oldArray, 4);
10. newArray[3] = 4; // Adding a new element
Accessing an element means retrieving the value stored at a specific index in an array. Java
arrays use zero-based indexing, meaning the first element is at index 0.
Example:
int[] numbers = {5, 10, 15, 20, 25};
System.out.println("Element at index 2: " + numbers[2]); // Output: 15
Updating an element means replacing an existing value at a given index with a new value.
Example:
int[] numbers = {5, 10, 15, 20, 25};
numbers[2] = 50; // Changing value at index 2
System.out.println("Updated element at index 2: " + numbers[2]); // Output: 50
Since Java arrays have a fixed size, elements cannot be directly deleted. However, deletion can
be simulated by:
Summary of Operations: