Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 4: Arrays, Jagged Arrays & the String Family

Lesson 5 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

4.1 Arrays — Objects on the Heap

A Java array is an object stored on the heap, even when it holds primitives. The reference lives on the stack; the contiguous element block lives on the heap along with a length field (a final field, not a method — contrast String.length()).

int[] a = new int[5];          // all elements default to 0
int[] b = {10, 20, 30};        // array literal
int c[] = new int[3];          // legal C-style, discouraged

Accessing a[5] on a 5-element array throws ArrayIndexOutOfBoundsException at runtime — Java always bounds-checks; there is no buffer overflow as in C.

4.2 2D & Jagged Arrays

Java has no true 2D arrays — a 2D array is an array of array references. This is why rows can have different lengths (jagged arrays):

int[][] matrix = new int[3][4];       // rectangular: 3 refs -> three int[4]
int[][] jagged = new int[3][];        // rows allocated separately
jagged[0] = new int[1];
jagged[1] = new int[2];
jagged[2] = new int[3];
for (int i = 0; i < jagged.length; i++) {
    for (int j = 0; j < jagged[i].length; j++)
        System.out.print(jagged[i][j] + " ");
    System.out.println();
}

Memory picture in words: matrix points to an array of 3 references; each reference points to a separate int[4] object elsewhere on the heap — rows are not contiguous with each other.

Utility methods from java.util.Arrays: sort, binarySearch (requires sorted input), fill, copyOf, equals, deepToString (for 2D printing).

4.3 String — Immutable by Design

A String is an immutable object: every "modifying" method (concat, toUpperCase, replace…) returns a new String, leaving the original untouched. Benefits: safe sharing between threads, cacheable hash code (used by HashMap), security (file paths/URLs can't be mutated after checks), and enabling the string pool.

The String Constant Pool (SCP): a special region inside the heap where literals are interned.

String s1 = "java";              // goes to the pool
String s2 = "java";              // REUSES the same pool object
String s3 = new String("java");  // forces a NEW heap object outside the pool
System.out.println(s1 == s2);         // true  (same reference)
System.out.println(s1 == s3);         // false (different objects)
System.out.println(s1.equals(s3));    // true  (same characters)
System.out.println(s1 == s3.intern());// true  (intern returns pool copy)

Golden rule: == compares references; equals() compares content. The number-one Java exam trap.

Compile-time constant folding: "ja" + "va" == "java" is true (folded into one literal), but s + "va" == "java" is false when s is a variable (computed at runtime, new object).

4.4 String vs StringBuilder vs StringBuffer

Concatenating inside a loop with + creates a new String every iteration — O(n²) total work. Use a mutable builder instead.

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-safeYes (via immutability)NoYes (synchronized methods)
SpeedSlow for repeated editsFastestSlower (locking overhead)
IntroducedJDK 1.0JDK 1.5JDK 1.0
Use whenFixed text, map keysSingle-threaded buildingShared mutable buffer (rare)

Key builder methods: append, insert, delete, reverse, setCharAt, toString, capacity() (default 16, grows as 2×old+2).

4.5 High-Yield String Methods

length(), charAt(i), substring(begin, endExclusive), indexOf, equalsIgnoreCase, compareTo (lexicographic, returns <0/0/>0), trim/strip, split(regex), toCharArray, contains, startsWith/endsWith, String.join, valueOf, format, chars() (IntStream).

Trap: substring(2, 5) includes index 2 but excludes 5 — length is 3.

🎯 Exam Focus

  1. What is a jagged array? How does Java implement 2D arrays internally? Write a program to add two matrices.
  2. Explain the String Constant Pool with a diagram. Why is s1 == s3 false but s1.equals(s3) true when s3 uses new String()?
  3. Why are Strings immutable in Java? List four advantages of immutability.
  4. Compare String, StringBuilder and StringBuffer on mutability, thread-safety and performance.
  5. Write a program to check whether a string is a palindrome (a) using StringBuilder.reverse() and (b) using a two-pointer loop.
  6. Predict output: "ja" + "va" == "java" vs s + "va" == "java" — explain constant folding.