← Java roadmap

Topic 4 of 30 · Beginner

Arrays & Strings

Fixed-size arrays, immutable Strings and StringBuilder.

Concept

An array has a fixed length set at creation and is indexed from 0. Accessing beyond it throws ArrayIndexOutOfBoundsException.

String is immutable — every change creates a new object. Literal strings are shared in the String pool.

Use StringBuilder when building strings in a loop; it's mutable and avoids creating many temporary objects.

Code (Java 21)

int[] scores = {78, 92, 65};
java.util.Arrays.sort(scores);
System.out.println(java.util.Arrays.toString(scores));

String a = "java", b = "java", c = new String("java");
System.out.println(a == b);       // true (pool)
System.out.println(a == c);       // false
System.out.println(a.equals(c));  // true

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(',');
System.out.println(sb.reverse());

Remember

  • Strings are immutable and thread-safe.
  • StringBuilder (fast) vs StringBuffer (synchronized).
  • array.length is a field; string.length() is a method.

Interview questions

Why is String immutable?

For security, safe sharing via the string pool, thread safety and cached hash codes used by HashMap keys.

Reverse a string without library reverse.

Convert to char[], swap from both ends moving inward, then build a new String.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Arrays & Strings” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.