Immutability and tidy-up methods
strip, isBlank and repeat arrived in Java 11. Older code uses trim(), which removes only characters with codes up to 32 (space and control characters).
A String is an object that holds a fixed sequence of characters. You create one with double quotes, join Strings with +, read characters by position starting at 0, compare contents with equals (never ==), and every method that seems to change a String actually returns a new one.
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.
Given String word = "programming";, print its length, its first and last characters, and the middle part without the first and last characters.
Given String email = "asha.k@example.com";, use indexOf and substring to print the user part (before @) and the domain (after @).
Given String a = "Level";, print whether it reads the same forwards and backwards ignoring case, by comparing its lower-case form with the reverse built from charAt in a simple sequence (the word has 5 letters).
Explain it without notes
Why is String immutable, and what does that let the JVM do?
Explain the difference between == and equals for Strings, and why == sometimes returns true for equal text.
What do 1 + 2 + "3" and "1" + 2 + 3 evaluate to, and why?
What is the difference between "", " " and null, and how do you test for each?
Expected output
ignored: hi
assigned: HI
[ Hello World ]
[Hello World]
contains World: true
replace: HeLLo WorLd
repeat: ababab
"" isEmpty: true
" " isEmpty: false
" " isBlank: true