Java Arrays - Quick Notes
What is an Array?
An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays in
Java are objects and can hold both primitive and reference types.
Declaration of an Array:
Syntax:
dataType[] arrayName;
Example:
int[] numbers;
Initialization of an Array:
Syntax:
arrayName = new dataType[size];
or
dataType[] arrayName = {value1, value2, ...};
Example:
int[] numbers = new int[5];
int[] numbers = {10, 20, 30, 40, 50};
Accessing Array Elements:
Elements are accessed using index numbers starting from 0.
Example:
System.out.println(numbers[0]); // Outputs 10
Example Program:
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(numbers[i]);
Multi-Dimensional Arrays:
Java supports multi-dimensional arrays (e.g., 2D arrays).
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Enhanced for Loop:
You can use the enhanced for loop to iterate arrays:
for (int num : numbers) {
System.out.println(num);
Important Points:
- Array size is fixed and cannot be changed after creation.
- Arrays can store objects too, e.g., String[].
- Always check for ArrayIndexOutOfBoundsException.