01
What is a String?
- A
Stringis a class injava.lang, even though Java lets you create one with literal syntax like a primitive. - Immutable. Once built, its characters never change.
,,+— - Backed by a char sequence. Internally a String wraps an array of characters, which is exactly why it's fixed-length once created.
02
Creating Strings
There are two ways to create a String, and they behave differently under the hood — which matters the moment you start comparing them.
String literal
String a = "hello";
Checked against a special pool of Strings first. If "hello" already exists there, the reference is reused — no new object is created.
The new keyword
String b = new String("hello");
Always creates a fresh object on the heap and memory area
03
Immutability & the String Pool
Because Strings can't change, Java is free to let identical literals safely share one copy. That shared cache is the String Pool.
Two literals
String x = "cat";
String y = "cat";
x and y points to same memory area
x == y → true
One literal, one new
String p = "cat";
String q = new String("cat");
p and q points to different memory area
p == q → false
Why concatenation "changing" a String is an illusion
String greeting = "Hi";
greeting = greeting + " there"; // "Hi" is untouched — a brand-new
// String "Hi there" is created,
// and greeting is re-pointed to it
04
Comparing Strings
This is the single most common source of String bugs: == and .equals() ask two different questions.
== — same object?
String a = new String("cat");
String b = new String("cat");
a == b; // false — two different objects
.equals() — same characters?
String a = new String("cat");
String b = new String("cat");
a.equals(b); // true — same character content
Rule of thumb
Always compare String content with
.equals(). Reserve == for checking whether two references point to the exact same object — rarely what you actually want with Strings.
05
Common Methods
A handful of methods cover the vast majority of everyday String work — every one of them returns something new rather than editing in place.
| Method | What it does | Example |
|---|---|---|
length() | Number of characters | "hello".length() → 5 |
charAt(i) | Character at index i | "hello".charAt(1) → 'e' |
substring(a, b) | Characters from index a up to, not including, b | "hello".substring(1,4) → "ell" |
indexOf(s) | First position of s, or -1 if absent | "hello".indexOf("l") → 2 |
toUpperCase() / toLowerCase() | New String with case changed | "Hi".toUpperCase() → "HI" |
trim() / strip() | New String with leading/trailing whitespace removed | " hi ".trim() → "hi" |
replace(a, b) | New String with all occurrences of a replaced by b | "cat".replace('c','b') → "bat" |
split(regex) | Breaks the String into an array by a delimiter | "a,b,c".split(",") → [a, b, c] |
contains(s) | True if s appears anywhere inside | "hello".contains("ell") → true |