Arrays and Strings · Introduction to Java Programming

Array Length

Watch lectures

Array Length

1. What .length Is (beginner)

.length = box count (fixed at new). Field (no brackets!) on arrays. Last valid index is always length-1. Beginners: arrays use .length, Strings use .length(), ArrayList uses .size() — three different forms!

2. Code — Loop the Safe Way

int[] marks = {80, 90, 70};
System.out.println(marks.length); // 3 (count, not last index!)
for (int i = 0; i < marks.length; i++) { // < (not <=!) — safe pattern
    System.out.println(marks[i]);
}
// 2-D: rows then cols!
int[][] m = {{1,2,3},{4,5,6}};
System.out.println(m.length);    // 2 (rows)
System.out.println(m[0].length); // 3 (cols of row 0)

3. Trap Table (exam favourite!)

Code Correct? Why
i < arr.length Yes 0 to length-1
i <= arr.length NO → crash! arr[length] out of bounds!
arr.length() NO → error! arrays: field, no ()
"hi".length NO → error! String: method with ()
list.length NO → error! ArrayList: .size()

4. length Can't Change

new int[3] stays 3 forever (final field). Need growable? ArrayList (next topics).

5. Exam Points

  • Loop with < length + 2-D lengths — 5 marks, very frequent.
  • .length vs .length() vs .size() — 3-5 marks, favourite trap.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules