Arrays in Java: 1D, 2D, Jagged Arrays & Traversal
1. Topic Introduction
When you need to store marks for 60 students or represent a 3×3 matrix, creating 60 separate variables is impossible to maintain. Java arrays store fixed-size collections of elements of the same type under a single name—and importantly, in Java, every array is itself an object stored dynamically on the Heap!
A 1D array is a single row of identical numbered lockers starting at locker #0 (marks[0], marks[1], ...). A 2D array is a grid of lockers organized by floor (row) and room (column): matrix[row][col]. In Java, a 2D array is actually an array of 1D arrays—meaning each floor doesn't even need the same number of rooms (a Jagged Array)!
new, possess a read-only .length field (NOT .length() method!), and throw ArrayIndexOutOfBoundsException if indexed invalidly.3. Essential Exam Definitions
0.4. Detailed Technical Explanation & Syntax
One-Dimensional Arrays: Declaration, Allocation & Initialization
Unlike C/C++ where int a[5]; allocates array memory at declaration, in Java int[] arr; ONLY creates a reference variable on the Stack. Actual memory is allocated on the Heap via new (or an array initializer literal):
- Java automatically initializes numeric arrays to
0/0.0,booleanarrays tofalse, and object arrays tonull. - Array bounds are strictly checked at runtime: accessing
primes[5]throwsArrayIndexOutOfBoundsException. - Length is obtained via the property
primes.length(no parentheses, unlikeString.length()).
| int[] marks; // Preferred Java style (or int marks[];) |
| marks = new int[5]; // Allocates 5 ints on Heap (all default to 0) |
| int[] primes = {2, 3, 5, 7, 11}; // Declaration + initialization shorthand |
Two-Dimensional & Jagged Arrays
A 2D array is implemented in Java as an array of references to 1D arrays. You can allocate a rectangular matrix (new int[3][4]) or specify only the row count first (new int[3][]) and allocate each row separately to build a Jagged Array.
| int[][] matrix = new int[2][3]; // Rectangular 2x3 matrix |
| int[][] jagged = new int[3][]; // 3 rows, columns allocated separately |
| jagged[0] = new int[2]; |
| jagged[1] = new int[4]; |
| jagged[2] = new int[1]; |
5. Working Principle: Memory Layout of Arrays in Java
int[][] grid = new int[2][3];creates an outer array of 2 references (grid[0],grid[1]) on the Heap.- Each outer slot points to a separate 1D
int[3]array object on the Heap. grid.lengthgives the number of rows (2), whilegrid[i].lengthgives the column count of rowi(3, or variable for jagged arrays).
7. Complete Java Code Examples & Tracing
| 1 | public class ArrayDemo { |
| 2 | public static void main(String[] args) { |
| 3 | // 1D Array & Bubble Sort |
| 4 | int[] scores = {45, 12, 58, 30}; |
| 5 | for (int i = 0; i < scores.length - 1; i++) { |
| 6 | for (int j = 0; j < scores.length - 1 - i; j++) { |
| 7 | if (scores[j] > scores[j + 1]) { |
| 8 | int temp = scores[j]; |
| 9 | scores[j] = scores[j + 1]; |
| 10 | scores[j + 1] = temp; |
| 11 | } |
| 12 | } |
| 13 | } |
| 14 | System.out.print("Sorted 1D: "); |
| 15 | for (int s : scores) { |
| 16 | System.out.print(s + " "); |
| 17 | } |
| 18 | System.out.println(); |
| 19 | |
| 20 | // Jagged 2D Array |
| 21 | int[][] jagged = new int[3][]; |
| 22 | jagged[0] = new int[] {10, 20}; |
| 23 | jagged[1] = new int[] {30, 40, 50}; |
| 24 | jagged[2] = new int[] {60}; |
| 25 | |
| 26 | System.out.println("Jagged Array:"); |
| 27 | for (int[] row : jagged) { // Enhanced for-loop extracts 1D rows |
| 28 | for (int val : row) { |
| 29 | System.out.print(val + " "); |
| 30 | } |
| 31 | System.out.println(); |
| 32 | } |
| 33 | } |
| 34 | } |
Sorted 1D: 12 30 45 58 Jagged Array: 10 20 30 40 50 60
newlengthfor- Writing
int arr[5] = new int[5];— NEVER put size on the left-hand declaration side in Java! - Writing
scores.length()with parentheses (compile error —.lengthis a field for arrays;.length()is a method for Strings). - Accessing
scores[scores.length](off-by-oneArrayIndexOutOfBoundsException).
Advantages
- O(1) constant-time random access by index (
arr[i]). - Strict bounds checking prevents buffer-overflow bugs common in C/C++.
Limitations / Disadvantages
- Fixed capacity once allocated—cannot dynamically grow or shrink (use
VectororArrayListwhen dynamic sizing is required). - Stores only homogeneous elements of the declared type.
Real-World Applications
- Representing image pixel matrices, game boards, lookup tables, and adjacency matrices in graph algorithms.
Important KTU Exam Points
- Show BOTH declaration forms:
int[] a;(preferred) andint a[];. - Highlight how Java creates Jagged Arrays by specifying only the first dimension (
new int[3][]). - Remember
arr.length(array property) vsstr.length()(String method) vsvec.size()(Vector method).
Memory Techniques & Revision
- Length Trio:
array.length(no parens),string.length()(with parens),vector.size()(size method).
Common Pitfalls to Avoid
- Putting array size in the declaration (
int[5] a;). - Forgetting that
for (int x : arr) { x = 0; }does NOT modify the original array (xis a read-only local copy of the value!).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: A jagged array is a multidimensional array whose rows have different numbers of columns, possible because Java treats 2D arrays as arrays of 1D array references.
- Allocate row references first:
int[][] j = new int[2][];. - Allocate different column lengths per row:
j[0] = new int[2]; j[1] = new int[4];.
| int[][] j = new int[2][]; |
| j[0] = new int[]{1, 2}; |
| j[1] = new int[]{3, 4, 5, 6}; |
Quick Understanding Check
1. Which of the following is an INVALID array declaration in Java?
2. Given int[][] x = new int[3][4];, what does x.length return?