What is Array in Java?
Array is used to store multiple values of same data type in a single variable.
Arrays make data handling easier and more organized.
Array Declaration
Arrays are declared using square brackets.
int numbers[];
Array Initialization
Arrays can be initialized while declaration.
int numbers[] = {10, 20, 30};
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
Output
10 20 30
Access Array Elements
Array elements are accessed using index numbers.
public class Main {
public static void main(String[] args) {
int numbers[] = {100, 200, 300};
System.out.println(numbers[1]);
}
}
Output
200
Array index starts from 0.
Change Array Value
Array values can be modified using index.
public class Main {
public static void main(String[] args) {
int numbers[] = {10, 20, 30};
numbers[1] = 50;
System.out.println(numbers[1]);
}
}
Output
50
Array Length
length property returns total elements in array.
public class Main {
public static void main(String[] args) {
int numbers[] = {10, 20, 30, 40};
System.out.println(numbers.length);
}
}
Output
4
Loop Through Array
for loop is commonly used with arrays.
public class Main {
public static void main(String[] args) {
int numbers[] = {1,2,3,4,5};
for(int i = 0; i < numbers.length; i++){
System.out.println(numbers[i]);
}
}
}
Output
1 2 3 4 5
Enhanced For Loop
Enhanced for loop makes array traversal easier.
public class Main {
public static void main(String[] args) {
int numbers[] = {10,20,30};
for(int n : numbers){
System.out.println(n);
}
}
}
Output
10 20 30
Multidimensional Array
Multidimensional arrays store data in rows and columns.
public class Main {
public static void main(String[] args) {
int matrix[][] = {
{1,2},
{3,4}
};
System.out.println(matrix[0][1]);
}
}
Output
2
Array of Strings
Arrays can also store strings.
public class Main {
public static void main(String[] args) {
String names[] = {"Alex", "John", "Sam"};
for(String n : names){
System.out.println(n);
}
}
}
Output
Alex John Sam
Important Points About Arrays
- Arrays store same type of data
- Array size becomes fixed after creation
- Index starts from 0
- Arrays improve code organization
Advantages of Arrays
- Store multiple values efficiently
- Easy data management
- Fast access using index
- Useful for loops and collections
Common Errors
- ArrayIndexOutOfBoundsException
- Using invalid index
- Wrong loop condition
- Accessing uninitialized arrays
Complete Java Array Program
public class Main {
public static void main(String[] args) {
int marks[] = {85, 90, 95};
for(int m : marks){
System.out.println(m);
}
}
}
Output
85 90 95
Best Practices
- Use meaningful array names
- Use loops carefully
- Check array length before access
- Prefer enhanced for loop when possible
Conclusion
Arrays are one of the most important concepts in Java. They help developers store and manage multiple values efficiently. Understanding arrays is essential before learning collections and data structures.