📊 We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 1 · Lesson 3 of 15

0% Exit to course

Module 1 · Java from zero Lesson 3 of 15

Strings and StringBuilder

Learning objective

A String is immutable: every "change" builds a new object. That single fact is behind half the Java questions in a fresher interview.

The concept

A String in Java is immutable: every method that appears to change it returns a NEW string. That makes strings safe to pass around and it also means concatenating inside a loop builds a new string each round, which is how a fresher program becomes slow on a real file.

Use StringBuilder when you are assembling text in a loop — .append() then .toString() — and the built-in String methods the rest of the time: length, charAt, substring, indexOf, split, replace, trim, toUpperCase, and String.format or %s for output. equalsIgnoreCase is what you want for comparing user input.

Java
String s = "Hello";
System.out.println(s.length());          // 5
System.out.println(s.toUpperCase());     // HELLO
System.out.println(s.substring(1, 3));   // el
System.out.println(s.contains("ell"));   // true

// Building many Strings in a loop? StringBuilder avoids the copies.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append("-");
System.out.println(sb.toString());

Common mistakes

The mistake is == for string comparison, and the second is string concatenation inside a loop over ten thousand rows. Both are common enough that interviewers ask about them by name, so learn the reason rather than the rule.

Worked example

Concatenating in a loop of 10000 rows creates 10000 discarded Strings; StringBuilder appends into one buffer and is the version to use. equals() compares content, == compares references — a distinction that shows up in every written test.

Your practice task

Reverse a sentence, count the words and replace one word — first with String methods, then with StringBuilder, and note the difference in readability.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A String in Java is immutable: every method that appears to change it returns a NEW string.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.

Next recommended course Python for Absolute Beginners