Module 5: Java ArraysBeginner24 min read
One-Dimensional, 2D & Jagged Arrays
Declare, initialize, and traverse 1D, 2D, and jagged arrays, and understand fixed-size heap allocation.
Key Takeaways & Core Concepts
- Multidimensional & Jagged Arrays: A 2D array
int[][]is actually an array of references to 1Dint[]arrays on the Heap. Therefore, each row can have a different length (a Jagged Array).
Introduction
An array in Java is a fixed-size, homogeneous object allocated on the Heap that stores elements in contiguous indexed slots. Every array in Java—even an array of primitives like int[]—is an Object with a final int length field.
1D Sorting & 2D Jagged Matrix
1import java.util.Arrays;
2
3public class Main {
4 public static void main(String[] args) {
5 int[] scores = {78, 92, 85, 99, 64};
6 Arrays.sort(scores);
7 System.out.println("Sorted: " + Arrays.toString(scores));
8
9 int[][] jagged = {
10 {1, 2},
11 {3, 4, 5},
12 {6}
13 };
14 for (int[] row : jagged) {
15 System.out.println(Arrays.toString(row));
16 }
17 }
18}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: `Arrays.sort()` uses Dual-Pivot Quicksort (O(n log n) average) for primitives.
Detailed Theory: Memory Layout & Bounds Safety
- When you execute
int[] scores = new int[5];, the JVM allocates contiguous memory on the Heap and initializes every slot to its type's default (0forint,falseforboolean,nullfor objects). - Unlike C/C++, Java checks array bounds on every access. Indexing
scores[5]orscores[-1]throwsArrayIndexOutOfBoundsExceptioninstead of silently corrupting adjacent memory. - Multidimensional & Jagged Arrays: A 2D array
int[][]is actually an array of references to 1Dint[]arrays on the Heap. Therefore, each row can have a different length (a Jagged Array).
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)