Arrays in Java
Arrays in Java
An array is a collection of similar data types stored in contiguous memory locations. Arrays are used
to store multiple values in a single variable instead of declaring separate variables for each value.
or
dataType[] arrayName = new dataType[size]; // Declaring and Allocating memory in one step
or
Syntax
Use Case
System.out.println("Array Elements:");
Output
Array Elements:
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
Syntax
or
Use Case
Used in matrix operations, game development (grid-based games like Chess, Tic-Tac-Toe), and storing
tabular data.
Example: 2D Array (Matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Output
2D Array (Matrix):
123
456
789
4.3 Jagged Arrays
A jagged array is an array where each row can have a different number of columns.
Syntax
Use Case
Used when memory optimization is needed, such as in irregular data structures like triangle
matrices.
System.out.println("Jagged Array:");
System.out.println();
Output
Jagged Array:
12
345
6789