Arrays in Java are used to store multiple values in a single variable, rather than declaring separate variables for each value. They allow you to store homogeneous (same type) data elements, making it easier to manage large amounts of data.
π§ What is an Array?
An array is a collection of similar data elements stored at contiguous memory locations. You can access array elements using indices.
π️ Types of Arrays in Java
-
Single-dimensional array – A simple list of values.
-
Multi-dimensional array – An array of arrays, like a matrix.
1️⃣ Single-Dimensional Array
A single-dimensional array is like a list of items.
2️⃣ Multi-Dimensional Array
Multi-dimensional arrays are arrays of arrays, and they can represent things like tables or matrices.
Example of 2D Array (Matrix):
π§π» Array Operations
Accessing Array Elements
Arrays are accessed using indices. The index starts from 0.
Array Length
You can get the length of an array using the length
property.
Traversing an Array (Looping through the elements)
π§ͺ Code Example: Single-Dimensional Array
π§ͺ Code Example: Multi-Dimensional Array
π Array Initialization
Arrays can be initialized in two ways:
-
Declaration with Initialization:
-
Declaration with
new
Keyword:
π§π« Array Methods (Useful for advanced users)
-
Arrays.sort(array)
: Sorts the array in ascending order. -
Arrays.toString(array)
: Converts an array into a string representation.
π Summary Table
Array Type | Example | Access |
---|---|---|
1D Array | int[] numbers = {1, 2, 3}; | numbers[0] |
2D Array | int[][] matrix = {{1,2},{3,4}}; | matrix[1][1] |