Introduction
In Java, arrays are one of the most commonly used data structures that allow you to store multiple values of the same type in a single variable. Instead of declaring separate variables for each value, arrays make it easier to manage large amounts of data efficiently.
For example, if you need to store the marks of 5 students, using an array is far more convenient than creating 5 different variables.
πΉ What is an Array in Java?
An array in Java is a container object that holds a fixed number of elements of the same data type.
Each element in the array is accessed by its index, starting from 0.
π Syntax:
datatype[] arrayName = new datatype[size];
π Example:
int[] marks = new int[5];
This statement creates an integer array named marks that can hold 5 elements (indexes 0 to 4).
πΉ Initializing an Array
You can initialize an array in two ways:
1️⃣ Using the new keyword:
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
2️⃣ Direct initialization:
int[] numbers = {10, 20, 30};
πΉ Accessing Array Elements
Each element in an array can be accessed using its index number.
π Example:
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[2]); // Output: 30
πΉ Array Length Property
You can find the total number of elements in an array using the .length property.
π Example:
System.out.println("Array length: " + numbers.length);
πΉ Traversing an Array
You can use loops to display or process array elements.
πΈ Using a for loop:
int[] marks = {75, 80, 92, 68, 88};
for(int i = 0; i < marks.length; i++) {
System.out.println("Mark " + (i+1) + ": " + marks[i]);
}
πΈ Using a for-each loop:
for(int mark : marks) {
System.out.println(mark);
}
πΉ Multi-Dimensional Arrays
Java also supports multi-dimensional arrays, such as 2D arrays used to store data in matrix form.
π Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // Output: 6
πΉ Advantages of Arrays
✅ Easy to store multiple values of the same type.
✅ Access elements directly using index.
✅ Efficient memory management.
πΉ Limitations of Arrays
❌ Fixed size — cannot change once declared.
❌ Only stores elements of the same type.
❌ Lacks advanced data manipulation methods like lists.
πΉ Example Program
Here’s a simple Java program that demonstrates arrays:
public class ArrayExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 88, 92};
int total = 0;
for (int mark : marks) {
total += mark;
}
double average = (double) total / marks.length;
System.out.println("Average Marks: " + average);
}
}
π€ Output:
Average Marks: 86.6
πΉ Conclusion
Arrays in Java are a fundamental concept that every programmer must understand. They provide an efficient way to store and process data collections. However, for dynamic storage and more advanced operations, you can use classes like ArrayList from the Java Collections Framework.
Comments
Post a Comment