Strings
Lesson 9 of 20Strings look simple but never change — learn their favorite methods and when StringBuilder saves the day.
Text with superpowers
Strings are objects packed with helpers — and one big surprise: they can never be changed, only replaced.
Strings are objects
A String is a sequence of characters with built-in helpers: length(), charAt(i), equals(...).
Immutable
A String can never change — every "modification" builds a brand-new String.
StringBuilder changes
StringBuilder is the editable cousin — append, insert and reverse text in place.
equals, not ==
Compare text with s.equals(t); == compares references, not letters.
Why strings never change
Any edit to a String builds a new object in memory — the original text stays untouched.
String methods at work
Press play: length counts, charAt grabs, toUpperCase copies — and word itself never changes.
1public class StrDemo {2public static void main(String[] args) {3String word = "java";4int len = word.length();5char first = word.charAt(0);6String up = word.toUpperCase();78System.out.println("Length: " + len);9System.out.println("First: " + first);10System.out.println("Upper: " + up);11System.out.println(word);12}13}
The JVM loads the StrDemo class into memory.
Predict the output
StringBuilder grows in place — follow its appends before you guess.
1public class BuildUp {2public static void main(String[] args) {3StringBuilder sb = new StringBuilder("ab");4sb.append("cd");5sb.append("e");6System.out.println(sb);7System.out.println(sb.length());8String frozen = sb.toString();9System.out.println(frozen + "!");10}11}
Hint: append glues text onto the end. length() counts every character. toString() freezes the text into a String.
Match the string tools
Click a term, then click what it does to lock the pair.
Key takeaways
A String is an object full of helpers: length(), charAt(), equals(), toUpperCase().
Strings are immutable — "changing" one really builds a new String.
StringBuilder appends in place — ideal inside loops.
Compare text with equals(), never with ==.
word.toUpperCase() does not change word — catch the return value.