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

public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
// Length — how many characters?
System.out.println("Length: " + greeting.length()); // 13
// charAt — grab one character by position
System.out.println("First char: " + greeting.charAt(0)); // H
System.out.println("Last char: " + greeting.charAt(greeting.length() - 1)); // !
// substring — cut out a piece
System.out.println("Sub: " + greeting.substring(0, 5)); // Hello
System.out.println("From 7: " + greeting.substring(7)); // World!
// Case changes
System.out.println("Upper: " + greeting.toUpperCase()); // HELLO, WORLD!
System.out.println("Lower: " + greeting.toLowerCase()); // hello, world!
// Finding & checking
System.out.println("Contains 'World': " + greeting.contains("World"));
System.out.println("Starts with 'Hello': " + greeting.startsWith("Hello"));
System.out.println("Index of 'W': " + greeting.indexOf('W'));
}
}
Output
Length: 13
First char: H
Last char: !
Sub: Hello
From 7: World!
Upper: HELLO, WORLD!
Lower: hello, world!
Contains 'World': true
Starts with 'Hello': true
Index of 'W': 7

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()

public class Main {
public static void main(String[] args) {
// equals() vs ==
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println("a == b: " + (a == b)); // true (same pool object)
System.out.println("a == c: " + (a == c)); // false! (different objects)
System.out.println("a.equals(c): " + a.equals(c)); // true (same content)
// String.format — like a template with blanks to fill in
String name = "Luna";
int score = 95;
String report = String.format("%s scored %d out of 100 (%.1f%%)",
name, score, (double) score);
System.out.println(report);
// Useful string operations
String messy = " too many spaces ";
System.out.println("Trimmed: '" + messy.trim() + "'");
String csv = "apple,banana,cherry";
String[] fruits = csv.split(",");
System.out.println("Second fruit: " + fruits[1]);
}
}
Output
a == b: true
a == c: false
a.equals(c): true
Luna scored 95 out of 100 (95.0%)
Trimmed: 'too many spaces'
Second fruit: banana

StringBuilder — When You Need Speed

public class Main {
public static void main(String[] args) {
// Bad: creating tons of throwaway String objects
// String result = "";
// for (...) result += something; // slow!
// Good: StringBuilder is like a whiteboard you can erase and rewrite
StringBuilder sb = new StringBuilder();
sb.append("I");
sb.append(" love");
sb.append(" Java");
sb.append("!");
System.out.println(sb.toString());
// You can also insert and delete
sb.insert(6, " learning");
System.out.println(sb.toString());
sb.delete(0, 2); // remove "I "
System.out.println(sb.toString());
// Reverse!
StringBuilder word = new StringBuilder("desserts");
System.out.println("Reversed: " + word.reverse());
}
}
Output
I love Java!
I love learning Java!
love learning Java!
Reversed: stressed
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

What does "hello".charAt(1) return?

Continue reading

Static ArraysData Structure
A row of numbered boxes — fast to grab, fixed in size
Trie (Prefix Tree)Data Structure
Insert, search, autocomplete
Operators & ExpressionsConditionals