Arrays
Memory Structure of Arrays
- Array are objects which are always created in heap memory
- The reference variable (e.g., ‘A’) can be in stack or heap
- Total memory = size of array × size of data type
- Two-dimensional arrays are objects
- Can be regular (same column count) or jagged (different column counts)
One Dimensional
Initialization of 1D Arrays
- Specifying Size (n is the size)
int[] Arrayname = new int[n];
or
Arrayname = new int[n]; - Direct Initialization
int[] Arrayname = {1, 2, 3, 4, 5};
System.out.println(Arrayname[2]); // prints 2 Accessing elements (1D)
-
Array length:
Arrayname.length -
For Loop
// Forward traversal for(int i = 0; i < Arrayname.length; i++) { System.out.println(A[i]); } // Reverse traversal for(int i = Arrayname.length-1; i >= 0; i--) { System.out.println(A[i]); } -
For-Each Loop
for(int x : Arrayname) { System.out.println(x); }
Two Dimensional
- Structure:
reference -> array of references -> arrays of elements
Initialization of 2D Arrays
- Specifying Size
int[][] Arrayname = new int[3][4]; // Creates 3 rows, 4 columns
or
int Arrayname[][] = new int[3][4]; // Creates 3 rows, 4 columns - Direct Initialization
int[][] Arrayname = {
{1, 2, 3, 4},
{2, 4, 6, 8},
{3, 5, 7, 9}
};
System.out.println(Arrayname[2]); // prints 2 - Split Declaration and Initialization
int[][] Arrayname; // Reference declaration
Arrayname = new int[3][4]; // Array creation Accessing elements (2D)
- For Loop
for(int i = 0; i < Arrayname.length; i++) { // Rows
for(int j = 0; j < A[0].length; j++) { // Columns
System.out.println(A[i][j]);
}
System.out.println("\n"); // New line after each row
} - For-Each Loop
for(int[] x : Arrayname) { // x is reference to each row array
for(int y : x) { // y gets actual elements
System.out.println(y);
}
} Jagged Arrays (Ragged Arrays)
- Arrays where rows can have different lengths
- Each row can contain different number of elements
- Useful for optimizing memory when rows need different sizes
int[][] A = new int[3][]; // Only create row references
A[0] = new int[2]; // First row has 2 elements
A[1] = new int[4]; // Second row has 4 elements
A[2] = new int[3]; // Third row has 3 elements