🔒 Strings are immutable
In Java, String objects cannot be changed after creation. Every method that appears to modify a string — trim(), toUpperCase(), replace() — actually returns a new String object. The original is untouched.
- Strings are safe to share across threads without synchronisation.
- The JVM can cache string literals in the String Pool — identical literals share one heap object.
- Concatenating strings in a loop (
s = s + x) creates a new object each iteration — useStringBuilderinstead.
🔤 Core String methods
Meera sanitises PAN numbers from a CSV (leading/trailing spaces, mixed case) before validation, then processes city names extracted from a comma-delimited config.
| Method | Returns | Example |
|---|---|---|
trim() | New String, leading/trailing whitespace removed | " hi ".trim() → "hi" |
strip() | Like trim() but Unicode-aware (Java 11+) | " hi ".strip() → "hi" |
length() | int — number of chars | "hello".length() → 5 |
toUpperCase() | New String in UPPER CASE | "abc".toUpperCase() → "ABC" |
contains(s) | boolean | "hello".contains("ell") → true |
replace(old, new) | New String with all occurrences swapped | "aaa".replace("a","b") → "bbb" |
startsWith(s) / endsWith(s) | boolean | "pan.csv".endsWith(".csv") → true |
indexOf(c) | First index of char, or -1 | "meera".indexOf('e') → 1 |
substring(from, to) | New String [from, to) | "hello".substring(1,4) → "ell" |
split(regex) | String[] | "a,b".split(",") → ["a","b"] |
🏗️ StringBuilder — building the receipt
Concatenating strings with + in a loop creates a new object every iteration — O(n²) allocations. StringBuilder maintains a single mutable buffer and amortises the cost to O(n). Use it whenever you're building a string across multiple steps.
append(x)— adds any type to the buffer; returnsthisfor chaining.insert(idx, x)— inserts at a specific position.delete(from, to)— removes chars in range[from, to).reverse()— reverses the buffer in place.length()— current character count.toString()— produces the final immutableString.
StringBuilder.java so java.lang.StringBuilder is referenced with its full name to avoid a name collision with the class itself. In real code just use StringBuilder directly.🎨 String formatting
Java offers three equivalent ways to produce formatted strings. Meera uses all three in different contexts: printf for console output, String.format when she needs a String object to store, and formatted (Java 15+) as a cleaner alternative to String.format.
| Specifier | Type | Example | Output |
|---|---|---|---|
%s | String / any object | "%s".formatted("hi") | hi |
%d | int / long | "%05d".formatted(42) | 00042 |
%f | float / double | "%.2f".formatted(3.1) | 3.10 |
%,f | double with grouping | "%,.2f".formatted(1250000.5) | 1,250,000.50 |
%-20s | Left-aligned, width 20 | "%-20s".formatted("EMI") | EMI |
%n | Platform line separator | Preferred over \n in format strings | (newline) |
⚖️ String comparison rules
This is one of the most common Java interview topics and a real source of bugs.
== to compare String content== compares references (are these two variables pointing to the same object?). .equals() compares content. Two String objects with identical text will return false for == if they are different objects on the heap.
| Method | What it compares | Case-sensitive? |
|---|---|---|
a == b | Reference identity | N/A — don't use for content |
a.equals(b) | Content, character by character | Yes |
a.equalsIgnoreCase(b) | Content, ignoring case | No |
a.compareTo(b) | Lexicographic order; 0 means equal | Yes |
a.compareToIgnoreCase(b) | Lexicographic order; 0 means equal | No |
⚠️ Common mistakes
"hello" == new String("hello") is false — they are different objects. Always use .equals() for content comparison. The JVM string pool may make some == comparisons accidentally true, which makes the bug even harder to spot.s = s + item creates a temporary String and discards it, causing O(n²) allocations. Inside any loop that builds a string, always use StringBuilder.append(). The compiler won't warn you.name.trim() when name is null throws NPE. Guard with if (name != null), use Objects.requireNonNullElse(name, ""), or flip to "fallback".equals(name) (safe even when name is null)."hello".substring(1, 4) returns "ell", not "ello". The second argument is exclusive — the character at that index is NOT included. Mnemonic: [from, to) like array slices in Python.🧠 Quick check
name.toUpperCase(). What happens to the original name variable?StringBuilder instead of + when building a string inside a loop?"hello".substring(1, 4) return?1,250,000.50 from 1250000.5?🎤 Interview Q&A
String immutable?Three design reasons: (1) Thread safety — immutable objects can be shared across threads without locks. (2) String pool — the JVM can safely deduplicate identical string literals in memory. (3) Security — class names, file paths, and network addresses passed as strings can't be mutated after validation. The trade-off: building strings by concatenation is expensive, hence StringBuilder.
String and StringBuilder?String is immutable: every "modification" creates a new object. StringBuilder is mutable: it holds a resizable char array and appends/deletes in place. Use String as your default; switch to StringBuilder when assembling a result across multiple concatenations (especially in loops). StringBuffer is the thread-safe but slower alternative to StringBuilder.
== comparisons?The String Pool (interning pool) is a special heap region where the JVM stores one copy of each unique string literal. When you write String a = "hello" and String b = "hello", both variables point to the same pooled object, so a == b happens to be true. But new String("hello") bypasses the pool and always creates a fresh object on the main heap, so a == new String("hello") is false. This inconsistency is why you must always use .equals() for content comparison.
null?Three patterns: (1) Null guard: if (name != null) name.trim(). (2) Literal-first comparison: "ADMIN".equals(role) — safe even when role is null, returns false instead of NPE. (3) Objects utility: Objects.requireNonNullElse(name, "") replaces null with an empty string. Pattern 2 is the most common idiom in interview code.
StringBuilder for + — so why does concatenating in a loop still cause O(n²) allocations?The Java compiler optimises single-expression concatenation like "a" + b + "c" into a single StringBuilder chain. But in a loop, each iteration is a separate expression: result = result + item compiles to result = new StringBuilder(result).append(item).toString(). A new StringBuilder and a new String are created every pass. After n iterations you've built 1 + 2 + 3 + … + n characters — O(n²) total work. Declaring one StringBuilder outside the loop and calling .append() inside is the correct fix.
✅ Key takeaways
- Strings are immutable — every method returns a new object; the original is unchanged.
- Always compare string content with
.equals()or.equalsIgnoreCase(), never==. - Use
StringBuilderwhen building strings across multiple steps or in a loop. String.format(),printf(), and.formatted()are interchangeable — choose based on whether you need aStringobject or direct console output.substring(from, to)is exclusive atto— the character at indextois not included.split()accepts a regex;","is fine, but"."must be escaped as"\\.".
You've finished Arc A — Core Java!
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →