Lesson 37 min read
Strings
Words, sentences, and the tricks you can do with them
Strings — More Than Just Text
A String in Java is like a necklace made of character beads — under the hood it's stored as an array of characters. Each bead (character) has a position number starting at 0. The word "Hello" has 5 beads: H is at position 0, e at 1, l at 2, l at 3, and o at 4.
Strings in Java are immutable — once you create one, you can't change it. Every time you "modify" a string, Java actually creates a brand new one behind the scenes. It's like how you can't erase ink from paper — you just get a new piece of paper.
Essential String Methods
The Great == vs .equals() Debate
This trips up everyone when they start Java. Here's the deal:
==checks if two variables point to the exact same object in memory. It's like asking "are these two keys for the same locker?".equals()checks if two strings have the same content. It's like asking "do these two pages have the same words on them?"
Most of the time, you want .equals(). Using == on strings can give you weird surprises because Java sometimes reuses string objects and sometimes doesn't.
equals() vs == and String.format()
StringBuilder — When You Need Speed
Note: If you're building a string inside a loop (like joining 1,000 names together), always use StringBuilder. Regular string concatenation with
+ creates a new String object every time, which is like rewriting an entire book just to add one word. StringBuilder is like using a whiteboard — you just keep adding to it.Quick check
Continue reading