In Java, an array is a collection of elements of the same type stored in a single variable. It helps in organizing and managing data efficiently. There are different types of arrays in Java, each with its own purpose.
- Single-Dimensional Array: A single-dimensional array is the most basic type of array in Java. It stores elements in a linear form (like a list).
1 |
int[] numbers = {1, 2, 3, 4, 5}; |
Here, numbers
is an array that holds five integer values.
1 2 |
int[] arr = new int[5]; // Declares an array of size 5 arr[0] = 10; // Assigns value 10 to the first element |
Use case: Storing multiple values of the same type, like student marks or product prices.
- Multi-Dimensional Array: A multi-dimensional array is an array of arrays. The most common type is the 2D array, which can be thought of as a table with rows and columns.
1 2 3 4 5 |
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; |
This represents a 3×3 matrix (3 rows and 3 columns).
1 2 |
int[][] table = new int[2][3]; // 2 rows, 3 columns table[0][0] = 1; // Assigns 1 to the first row, first column |
Use case: Storing grid-like data, such as a chessboard, a tic-tac-toe game, or tables.
- Jagged Array: A jagged array is a multi-dimensional array where each row can have a different number of columns.
1 2 3 4 5 |
int[][] jaggedArr = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} }; |
Here, the first row has 3 elements, the second row has 2 elements, and the third row has 4 elements.
Use case: When rows have different numbers of elements, such as storing test scores for students who took different numbers of exams.
- Array of Objects: Instead of storing primitive values like
int
ordouble
, an array can hold objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Student { String name; Student(String name) { this.name = name; } } public class Main { public static void main(String[] args) { Student[] students = new Student[3]; // Array of Student objects students[0] = new Student("Alice"); students[1] = new Student("Bob"); students[2] = new Student("Charlie"); System.out.println(students[0].name); // Outputs: Alice } } |
Use case: Storing multiple objects, like a list of students, employees, or products.
- Anonymous Arrays: An anonymous array is created without explicitly declaring its type and size.
1 2 3 4 5 6 7 |
displayArray(new int[]{10, 20, 30}); public static void displayArray(int[] arr) { for (int num : arr) { System.out.print(num + " "); } } |
Here, we pass an anonymous array {10, 20, 30}
directly to the displayArray
method.
Use case: When you need a temporary array for one-time use.