Java Arrays β Complete Guide with Syntax, Examples & Best Practices
Introduction β Why Arrays Matter in Java
Imagine needing to store the marks of 100 students. Creating 100 separate variables would be chaotic.
Thatβs where arrays come in β allowing you to store multiple values of the same type in a single variable.
By the end of this article, you’ll learn:
- What arrays are and how they work in Java
- Syntax for declaring, initializing, and accessing arrays
- How to loop through arrays using
forandfor-each - Real-world examples, best practices, and common pitfalls
What is an Array in Java?
An array is a container object that holds a fixed number of elements of the same type, accessible using an index.
Important Note: Java arrays have zero-based indexing.
Declaring and Initializing Arrays
1. Declaration Only
int[] numbers;
2. Declaration + Memory Allocation
int[] numbers = new int[5]; // holds 5 integers (default 0)
3. Declaration + Initialization with Values
int[] numbers = {10, 20, 30, 40, 50};
Explanation:
int[]β declares an integer array{}β initializes it with valuesnew int[5]β allocates space for 5 elements with default values
Accessing Elements in Arrays
int[] scores = {90, 85, 70};
System.out.println(scores[1]); // 85
Explanation:
- Index
0= first element - Index
1= second element - Accessed using
array[index]
Accessing an index outside bounds throws ArrayIndexOutOfBoundsException.
Looping Through Arrays
1. Standard for Loop
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
2. Enhanced for Loop (for-each)
for (int score : scores) {
System.out.println(score);
}
Explanation:
scores.lengthgives array size- Enhanced loop simplifies read-only traversal
Modify Array Elements
int[] numbers = {1, 2, 3};
numbers[0] = 10;
System.out.println(numbers[0]); // 10
Arrays are mutable: you can update any index with a new value.
Real-World Example: Finding Maximum in Array
int[] data = {12, 45, 22, 89, 5};
int max = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
System.out.println("Max: " + max);
Explanation:
- Compares each value with
max - Updates
maxif a larger value is found
Multi-Dimensional Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // 6
Explanation:
- 2D array = array of arrays
- Accessed using
array[row][column]
Commonly used in grid-based apps, games, and mathematical computations.
Best Practices for Java Arrays
Tips:
- Always check
.lengthbefore accessing indices - Prefer
ArrayListfor dynamic resizing needs - Use enhanced for loop when not modifying values
Pitfalls:
- Arrays have fixed size β cannot grow after creation
- Be careful with off-by-one errors (
i <= array.length)
Java Arrays vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type | Primitive & Object | Objects only (generic) |
| Syntax | Simpler | More flexible |
| Performance | Faster | Slightly slower |
Summary
Java arrays are essential for storing fixed-size groups of related values. Mastering them lets you write efficient, clean, and logical Java code.
Key Takeaways:
- Arrays store multiple values of the same type
- Indexing starts at 0
- Use loops to access or modify data
- For dynamic storage, consider using collections like
ArrayList
FAQs β Java Arrays
Can Java arrays hold different data types?
No. Arrays in Java can only hold elements of the same type.
What is the default value of an array element?
int,long,byte,shortβ0float,doubleβ0.0booleanβfalsecharβ'\u0000'(null character)- Object types β
null
Can I change the size of an array?
No. Once created, the size of an array is fixed. Use ArrayList for resizable collections.
How to get the length of an array?
Use array.length (no parentheses β itβs a property, not a method).
How to copy one array into another?
Use System.arraycopy() or Arrays.copyOf() for efficient copying.
Share Now :
