In Java, an array is a powerful and foundational data structure that allows to store multiple values of the same type in a single variable. Arrays provide a systematic way to manage large collections of data efficiently, especially when the number of elements is known in advance.
An array in Java is a container object that holds a fixed number of elements of a single data type. Each element in the array is accessed using its index, which starts from 0.
Syntax:
dataType[] arrayName = new dataType[size];
Example:
int[] scores = new int[5]; // Declaration with size 5
scores[0] = 85;
Types of Arrays
Java supports two primary types of arrays:
Single-Dimensional Arrays
A linear list of elements.
Example: int[] numbers = {1, 2, 3, 4};
Multi-Dimensional Arrays
Arrays of arrays (e.g., 2D arrays or matrices).
Example: int[][] matrix = new int[3][3];
Array Initialization Methods
Static Initialization:
String[] fruits = {"Apple", "Banana", "Cherry"};
Dynamic Initialization:
double[] prices = new double[3];
prices[0] = 9.99;
Accessing Array Elements
Elements are accessed by their index position:
System.out.println(scores[2]); // Prints the 3rd element
Common Operations on Arrays
Traversal using for or for-each loop
Sorting using Arrays.sort(array)
Searching using Arrays.binarySearch(array, key)
Cloning with array.clone()
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
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
Key Characteristics
Arrays in Java are objects.
The length of an array is fixed and cannot be changed once declared.
The property array.length gives the total number of elements.
Java automatically initializes array elements with default values:
0 for numeric types
false for boolean
null for reference types
Official reference link:
1 :https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Top comments (0)