[!NOTE] Strings are arguably the most used object in Java programming. Because they are so common, Java handles them using special memory optimizations that often trip up beginners.
The String Pool Architecture
Strings in Java are objects, but they are specially cached in an area of memory called the String Pool to save space.
Because multiple variables might be pointing to the exact same String in memory, Strings are historically immutable (they cannot be changed once created). When you "modify" a String, you aren't actually modifying it; Java is destroying the old reference and creating a brand new String object in memory.
String a = "Hello";
String b = "Hello";
// Behind the scenes, 'a' and 'b' point to the exact same object in the String Pool to save RAM!
a = a + " World";
// Java creates a NEW string "Hello World", 'a' points to it. 'b' still points to "Hello".
5 Essential String Methods
Java provides dozens of built-in methods on the String class. Here are the 5 most crucial ones you will use daily:
| Method | Description | Example Code | Output |
|---|---|---|---|
.length() |
Returns the number of characters. | "Java".length() |
4 |
.equals() |
Compares string contents safely. | "ABC".equals("abc") |
false |
.trim() |
Removes leading/trailing spaces. | " Hi ".trim() |
"Hi" |
.indexOf() |
Finds first occurrence index. | "Hello".indexOf("l") |
2 |
.substring() |
Slices the string from X to Y. | "Apples".substring(0, 3) |
"App" |
[!CAUTION] Never use
==to compare Strings in Java! The==operator checks if two objects occupy the exact same physical memory address, NOT if their text is the same. Always usestringA.equals(stringB)to compare text values!
StringBuilder: For Heavy Lifting
Remember how Strings are immutable? If you write a loop that concatenates a string 10,000 times, Java will aggressively create and destroy 10,000 separate String objects in memory. This is devastatingly slow.
If you are doing heavy string concatenation in a loop, avoid the + operator. Use the mutable StringBuilder class.
// BAD: Creates 10,000 abandoned String objects in Heap memory
String result = "";
for (int i = 0; i < 10000; i++) {
result += i;
}
// GOOD: Modifies a single object in place. 100x faster execution!
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
String finalResult = sb.toString();