Useful JavaExtra· 35 min read

Strings in Depth & StringBuilder

Strings are everywhere — learn the methods you will use daily, why they cannot be changed, and how StringBuilder fixes slow joining.

What you will learn

  • Use the most common String methods
  • Understand that Strings are immutable
  • Build text efficiently with StringBuilder

The String toolbox

A String is a piece of text. You have used them since lesson one. Java gives every String a set of built-in methods for working with that text — checking its length, changing its case, finding parts of it, and more. Here are the ones you will reach for most.

MethodWhat it doesExample on "Hello"
length()Number of characters5
toUpperCase()All capitals"HELLO"
toLowerCase()All lowercase"hello"
charAt(1)Character at an index'e'
substring(1, 4)A slice (index 1 up to, not including, 4)"ell"
contains("ell")Is this text inside?true
replace("l", "L")Swap one part for another"HeLLo"
trim()Remove spaces at both ends(no spaces to remove)
Chaining several String methods together
String name = "  Asha Patel  ";

System.out.println(name.trim());                 // remove edge spaces
System.out.println(name.trim().toUpperCase());   // then capitalise
System.out.println(name.trim().length());        // count characters
System.out.println(name.contains("Patel"));      // search inside
System.out.println(name.trim().substring(0, 4)); // first four letters

Note: Output: Asha Patel ASHA PATEL 10 true Asha Each method returns a new String, so we can chain them: name.trim().toUpperCase() trims first, then capitalises the trimmed result. substring(0, 4) takes the characters at index 0, 1, 2 and 3 (it stops just before index 4), giving "Asha".

Watch out: Like arrays, String indexes start at 0. In "Hello", charAt(0) is the H and charAt(4) is the last o. Asking for charAt(5) throws a StringIndexOutOfBoundsException, because there is no character at index 5.

Strings cannot be changed (immutable)

Here is a surprise that trips up beginners: a String is immutable, which means once created it can never be changed. Methods like toUpperCase() do not edit the original — they build and return a brand-new String and leave the old one untouched.

A method returns a new String — you must store it
String greeting = "hello";
greeting.toUpperCase();              // result thrown away!
System.out.println(greeting);        // still lowercase

greeting = greeting.toUpperCase();   // store the new String back
System.out.println(greeting);        // now uppercase

Note: Output: hello HELLO The first toUpperCase() made a new "HELLO" but we did not keep it, so greeting stayed "hello". The second time we assigned the result back with greeting = ..., so now it prints "HELLO". Remember: String methods give back a new value, they never change the original.

Tip: Compare String text with .equals(...), not ==. == checks whether two variables point to the exact same object, which can be surprisingly false even for equal-looking text. "hi".equals(other) checks the actual characters — that is almost always what you want.

StringBuilder: when you join a lot of text

Because each + on Strings makes a new String, joining text inside a big loop is wasteful — Java keeps throwing away and rebuilding. For heavy text-building, use StringBuilder, a special object you can change in place. You append pieces, then call toString() once at the end.

Building one String efficiently with StringBuilder
StringBuilder sb = new StringBuilder();

for (int i = 1; i <= 5; i++) {
    sb.append(i);
    sb.append("-");
}

String result = sb.toString();
System.out.println(result);

Note: Output: 1-2-3-4-5- append added each piece onto the same StringBuilder, with no wasteful copies. At the end toString() turned it into a finished String. For a handful of joins, plain + is fine — reach for StringBuilder when you are building text inside a loop that runs many times.

Plain + vs StringBuilder

Joining text withCreates new copies?Best for
+ on StringsYes, a new String each timeA few values, simple cases
StringBuilder.appendNo — changes in placeLots of pieces, loops

Q. What does it mean that a String is immutable?

Answer: Immutable means unchangeable. toUpperCase(), replace() and friends return a new String; the original stays as it was, which is why you must store the result.

✍️ Practice

  1. Read a word with Scanner and print its length, its uppercase form, and its first character.
  2. Use a StringBuilder in a loop to build the text "*****" (five stars) and print it.

🏠 Homework

  1. Ask the user for a sentence, then print how many characters it has, the sentence in uppercase, and whether it contains the word "Java".
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →