Java Arrays
Learn how to store multiple values in a single variable using arrays in Java.
What is an Array?
An array is a container that holds a fixed number of values of the same type. Instead of creating separate variables for each value, you can store them all in one array.
Think of an array like a row of lockers. Each locker has a number (index) and can store one item. All lockers in the row hold the same type of items.
- Arrays store multiple values in a single variable
- All elements must be of the same data type
- Array size is fixed once created
- Array indexing starts from 0 (first element is at index 0)
💡 Important: Array indices start at 0, not 1. So a 5-element array has indices 0, 1, 2, 3, and 4.
Declaring and Creating Arrays
There are two ways to declare an array in Java. Let's see how to create an array of integers.
Example: Array Declaration Methods
public class ArrayExample {
public static void main(String[] args) {
// Method 1: Declare and create separately
int[] numbers;
numbers = new int[5];
// Method 2: Declare and create together
int[] marks = new int[5];
// Method 3: Declare, create, and initialize
int[] scores = {85, 90, 78, 92, 88};
System.out.println("Array created successfully!");
System.out.println("First score: " + scores[0]);
}
}
Array created successfully! First score: 85
Explanation:
int[] numbers- Declares an array variablenew int[5]- Creates an array with space for 5 integers{85, 90, 78, 92, 88}- Initializes array with values directlyscores[0]- Accesses the first element (index 0)
Accessing Array Elements
You can access array elements using their index number inside square brackets. Remember, indexing starts from 0.
Example: Accessing and Modifying Arrays
public class AccessArray {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
// Accessing elements
System.out.println("First fruit: " + fruits[0]);
System.out.println("Second fruit: " + fruits[1]);
// Modifying an element
fruits[2] = "Grapes";
System.out.println("Modified third fruit: " + fruits[2]);
// Getting array length
System.out.println("Total fruits: " + fruits.length);
}
}
First fruit: Apple Second fruit: Banana Modified third fruit: Grapes Total fruits: 4
Explanation:
fruits[0]- Accesses the first element (Apple)fruits[2] = "Grapes"- Changes the value at index 2fruits.length- Returns the total number of elements in the array
Looping Through Arrays
You can use loops to access all elements of an array without writing repetitive code.
Example: Using For Loop with Arrays
public class LoopArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Using traditional for loop
System.out.println("Using for loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// Using enhanced for loop (for-each)
System.out.println("\nUsing for-each loop:");
for (int num : numbers) {
System.out.println(num);
}
}
}
Using for loop: 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 Using for-each loop: 10 20 30 40 50
Explanation:
for (int i = 0; i < numbers.length; i++)- Traditional loop using indexfor (int num : numbers)- Enhanced for-each loop, simpler and cleaner- For-each loop automatically iterates through all elements without needing indices
Common Array Operations
1. Finding Sum of Array Elements
Calculate the total sum of all numbers in an array using a loop.
Example: Add all marks to get total score
2. Finding Maximum/Minimum
Loop through the array to find the largest or smallest value.
Example: Find highest marks or lowest temperature
3. Searching for an Element
Check if a specific value exists in the array using linear search.
Example: Check if a student name exists in the list
4. Copying Arrays
Create a duplicate of an array using loops or built-in methods.
Example: Backup original data before modifications
Common Array Mistakes to Avoid
- ArrayIndexOutOfBoundsException: Trying to access an index that doesn't exist (e.g., accessing index 5 in a 5-element array)
- Forgetting array size is fixed: You cannot add more elements than the declared size
- Not initializing array elements: If you don't assign values, numeric arrays contain 0, boolean contains false, and object arrays contain null
- Starting from index 1: Remember arrays start at index 0, not 1
⚠️ Tip: Always use array.length in loops instead of hardcoding the size. This prevents errors if array size changes.