Array in Java
In Java, an array is a fixed-size, ordered collection of elements of the same type. It allows you to store multiple values of the same data type under a single variable name. Arrays are widely used in Java for storing and manipulating data efficiently.
Types of Arrays
Single-Dimensional Array: A single-dimensional array, also known as a one-dimensional array, is the most common type of array. It represents a linear collection of elements, accessed by their index. The index starts from 0 and goes up to the length of the array minus one.
Multidimensional Array: A multidimensional array is an array of arrays, where each element can also be an array. Java supports two-dimensional and multi-dimensional arrays. For example, a two-dimensional array is like a table or grid with rows and columns.
Advantages of Arrays
Efficient Storage and Access: Arrays provide efficient storage and access to elements. Elements in an array are stored in contiguous memory locations, allowing for direct and fast access using index-based operations.
Easy Iteration: Arrays allow for easy iteration over elements using loops, making it convenient to perform operations on all elements of the array.
Random Access: Elements in an array can be accessed randomly using their index. This means you can directly access any element in the array without the need to traverse through other elements.
Compact Representation: Arrays provide a compact representation of data. They allow you to store multiple values of the same type under a single variable, reducing the need for multiple individual variables.
Simplified Data Manipulation: Arrays simplify data manipulation and operations such as sorting, searching, and mathematical computations. Many algorithms and data structures are based on or use arrays as a fundamental building block.
Single-Dimensional Array Example:
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(numbers[2]); // Output: 30
In this example, a single-dimensional array named numbers is created with a length of 5. Elements are assigned values using the index, and the value at index 2 is printed.
Multi-Dimensional Array Example (2D array)
int[][] matrix = new int[3][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
System.out.println(matrix[1][2]); // Output: 6
In this example, a two-dimensional array named matrix is created with a size of 3x3. Elements are assigned values using row and column indices, and the value at row 1, column 2 is printed.
Arrays in Java provide a powerful and efficient way to work with collections of elements. They offer simplicity, random access, and efficient storage, making them a fundamental data structure in Java programming.