KTU OOP Java2024 Scheme • 60M ESE
MODULE 1/Section 1: Introduction to Java

Arrays in Java: 1D, 2D, Jagged Arrays & Traversal

MEDIUM PRIORITY (Prep Guide)Official Syllabus~13 min study
Official KTU 2024 Syllabus Topics Covered Here
ArraysOne-dimensional and multidimensional arrays

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!

2. Start From Zero: Numbered Lockers in a Hallway vs Apartment Floors

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)!

Key Takeaway: Java arrays are zero-indexed Heap objects created with new, possess a read-only .length field (NOT .length() method!), and throw ArrayIndexOutOfBoundsException if indexed invalidly.

3. Essential Exam Definitions

Array
A fixed-length, indexed data structure (treated as a reference object in Java) that stores homogeneous elements in contiguous logical order starting at index 0.
Jagged (Ragged) Array
A multidimensional array in Java where individual rows are allocated independently with varying column lengths (e.g., row 0 has 2 elements, row 1 has 4 elements).

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, boolean arrays to false, and object arrays to null.
  • Array bounds are strictly checked at runtime: accessing primes[5] throws ArrayIndexOutOfBoundsException.
  • Length is obtained via the property primes.length (no parentheses, unlike String.length()).
Java Syntax Template
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.

Java Syntax Template
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

  1. int[][] grid = new int[2][3]; creates an outer array of 2 references (grid[0], grid[1]) on the Heap.
  2. Each outer slot points to a separate 1D int[3] array object on the Heap.
  3. grid.length gives the number of rows (2), while grid[i].length gives the column count of row i (3, or variable for jagged arrays).

7. Complete Java Code Examples & Tracing

1D Sorting + 2D Rectangular & Jagged Array TraversalArrayDemo.java
Demonstrates 1D array traversal, sorting using nested loops, 2D matrix printing, and jagged array row-by-row allocation.
1public 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}
Expected Output
Sorted 1D: 12 30 45 58 
Jagged Array:
10 20 
30 40 50 
60
Keywords:newlengthfor
Common Exam & Coding Mistakes
  • 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 — .length is a field for arrays; .length() is a method for Strings).
  • Accessing scores[scores.length] (off-by-one ArrayIndexOutOfBoundsException).

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 Vector or ArrayList when 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) and int a[];.
  • Highlight how Java creates Jagged Arrays by specifying only the first dimension (new int[3][]).
  • Remember arr.length (array property) vs str.length() (String method) vs vec.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 (x is 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?