Arrays & Strings
Strings
Complete lesson for Strings using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Strings
Section: Arrays & Strings. String immutability, the string pool, == vs equals, and StringBuilder vs StringBuffer.
String is a class, and it is immutable
Stringlives injava.lang. Once created, itschar/bytecontent never changes. Methods liketoUpperCase()return a new object.- String literals (
"hi") are interned in the string pool.new String("hi")forces a heap copy and is almost never what you want. - Java 9+ stores compact strings as
byte[](LATIN-1 or UTF-16), but you still think incharAt/ code points.
public class StringBasics {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // true (same interned literal)
System.out.println(a == c); // false (different object)
System.out.println(a.equals(c)); // true (same characters)
}
} == vs equals
- For references,
==tests identity (same object).equalsonStringtests character content (and is null-safe only if you call it on the non-null side).
| Check | == | equals |
|---|---|---|
| What it compares | Reference identity | Value (for String, content) |
"ab" == "a" + "b" | Often true (constant fold + intern) | Always true if content matches |
new String("x") == "x" | false | true |
| Null | s == null is safe | s.equals(...) NPEs if s is null |
| Use for strings? | Almost never | Yes — or Objects.equals(a, b) |
Core API you must know
length(),charAt(i),substring(start, end)(end exclusive),indexOf,contains,split,trim/strip(Java 11),isBlank(Java 11),repeat(Java 11),formatted(Java 15).substringin modern JDKs copies (no shared backing array). Empty string""has length 0 and is interned.
StringBuilder vs StringBuffer vs String
| Type | Mutable? | Thread-safe? | When to use |
|---|---|---|---|
String | No | Yes (immutable) | Keys, messages, APIs |
StringBuilder | Yes | No | Default choice for building text in one thread |
StringBuffer | Yes | Yes (synchronized) | Legacy shared builders; rarely needed now |
Advanced — Strings
Concatenation, intern, and complexity
s + tin a loop is O(n²) because each+may copy. The compiler rewrites *standalone*+chains toStringBuilder, but not across a loop. UseStringBuilderyourself.intern()returns the pooled instance. Do not intern every runtime string — it can leak metaspace/heap.StringhashCode is cached. That is why strings make decentHashMapkeys.- Never compare strings with
==in application code. Interviews will still ask when==happens to be true.
Tricky Interview Points
Q1) Why is String immutable?
Answer Security (paths, class names), thread-safety, string-pool sharing, and reliable hashCode for map keys. Methods return new strings instead of changing this.
Q2) == vs equals for String?
Answer == compares references. equals compares characters. Literals may share the pool so == can be true; never rely on that.
Q3) StringBuilder vs StringBuffer?
Answer Both are mutable. StringBuffer methods are synchronized (older, slower). StringBuilder is the Java 5+ default for single-threaded building.
Q4) What does substring(1, 4) return for "Java"?
Answer "ava" — begin inclusive, end exclusive. Length = 4-1 = 3.
Q5) Is String a primitive?
Answer No. It is a class. The language just gives literals and + concatenation extra support.
Q6) Why is + in a loop a performance bug?
Answer Each concatenation may allocate a new String and copy growing content, which is quadratic. Use StringBuilder.append.
Q7) What is the string pool?
Answer A heap area (since Java 7, in the regular heap) where interned String instances are reused so identical literals share one object.
Simple Programs
Reverse a string with StringBuilder
public class ReverseString {
public static void main(String[] args) {
String input = "LearnCodeGuru";
String reversed = new StringBuilder(input).reverse().toString();
System.out.println(reversed);
System.out.println(input.equalsIgnoreCase("learncodeguru"));
}
} Build vs + in a loop
public class BuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(' ');
}
System.out.println(sb.toString().strip());
}
} Problem Solving Tricks
- Call
equalson the literal:"OK".equals(s)never NPEs. - Use
Objects.equals(a, b)when either side may be null. isEmpty()islength() == 0.isBlank()also treats whitespace as empty (Java 11).- For interviews, implement palindrome / anagram / first unique char with
char[]or a frequency map. - Text blocks (
""") arrived in Java 15 — great for JSON/SQL samples.
Practice Programs List
- Count vowels and consonants in a line of text.
- Check palindrome after ignoring case and spaces.
- Implement
indexOfyourself for a character. - Split a CSV line and trim each part.
- Build the string
1,2,3,...,nwithStringBuilder(no trailing comma). - Show three cases where
==is true and three where onlyequalsis true.