Strings never change: methods return new ones
A String object can never change after it's created, which lets the JVM keep one shared copy of each string literal in the string pool. Every method that seems to change a String returns a new one, and intern() lets you put run-time Strings into the pool too.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program that builds the String "tea" in three ways (a literal, new String, and concatenation of a non-final variable) and prints, for each, whether it is == to the literal and whether it is equals to it.
Write a method static String capitalise(String s) that returns s with its first letter in upper case. Show that the caller's String is unchanged after the call.
Write a program with a final constant and a non-final variable that proves which concatenations the compiler folds. Print four labelled == results.
Explain it without notes
What is the string pool, what goes into it, and where does it live in a modern JVM?
Why is String immutable? Give at least three benefits.
Explain why "a" + "b" == "ab" is true but x + "b" == "ab" (with String x = "a";) is false.
What does intern() do, and when would you use it?
How many String objects can String s = new String("hello"); create?
Expected output
after ignoring the result: hello
s: HELLO, t: hello
u: hello world, t: hello
trim() with nothing to trim returns the same object: true
trim() with spaces returns a new object: true