Arrays in Java
Arrays are one of the most important data structures in Java. They allow you to store multiple values of the same type in a single variable, making your code more organized and efficient.
What is an Array in Java?
- An array is a container object that holds a fixed number of values of the same type.
- Each value in an array is called an element, and each element has an index starting from
0.
Example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // 30
Here, numbers is an array of integers. numbers[2] accesses the third element (index starts from 0).
Advantages of Using Arrays
- Organized Storage: Stores multiple values in a single variable.
- Efficient Access: Use an index to access or modify elements quickly.
- Memory Management: Arrays store homogeneous data efficiently.
- Easy Iteration: Works seamlessly with loops (for, while, enhanced for).
- Useful for Algorithms: Sorting, searching, and mathematical operations become simpler.
Visual Representation of the Array:
Index → 0 1 2 3 4
Value → [10] [20] [30] [40] [50]Array Declaration and Initialization
There are two main steps: declaration and initialization.
1. Declaration
int[] arr1; // Preferred way
int arr2[]; // Also valid
2. Initialization
arr1 = new int[5]; // Creates an array of 5 integers (default 0)
Declaration + Initialization in One Step
int[] scores = {90, 80, 70, 60, 50};
Example: Using Arrays
public class ArrayIntro {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = new int[5];
// Assign values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Access and print values
for(int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Points to Know :
- Arrays store homogeneous data in a single variable.
- Array size is fixed once created.
- Indexing starts at 0. Accessing an invalid index throws ArrayIndexOutOfBoundsException.
- Arrays are useful for loop-based operations and algorithm implementation.
- For dynamic data, consider ArrayList or other collections.
