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, built-in String methods, and String vs StringBuffer vs StringBuilder.
What is a String?
Stringis a class injava.lang, not a primitive. It stores a sequence of characters (Java 9+ compactbyte[]: LATIN-1 or UTF-16).- It is immutable: methods such as
toUpperCase()return a new object; the original never changes. - Literals (
"hi") go into the string pool.new String("hi")forces a separate heap copy and is almost never what you want. - Real-life examples: student name, email, OTP, password, file path, chat message.
| Idea | Meaning | Real-life mapping |
|---|---|---|
| Characters | Letters / digits / symbols | Letters in a name |
length() | How many characters | Password must be ≥ 8 |
| Index | Position from 0 | First letter of a name |
| Empty string | "" — length 0 | Blank form field |
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)
}
} Creating strings
- Literal:
String s = "Hello";(pooled). Constructor:new String("Hello")(new object). String.valueOf(x)converts numbers, chars, and objects.char[]can become aStringwithnew String(chars).- Java 15 text blocks (
""") keep multi-line JSON/SQL readable.
public class CreateString {
public static void main(String[] args) {
String name = "Ravi";
String fromChars = new String(new char[] {'J', 'a', 'v', 'a'});
String n = String.valueOf(42);
System.out.println(name + " " + fromChars + " " + n);
}
} == vs equals
==tests identity (same object).equalsonStringtests character content.- Call equals on the literal (
"OK".equals(s)) so a nullsdoes not throw. Or useObjects.equals(a, b).
| 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) |
String built-in methods — inspect and search
- Call instance methods as
s.method(...). Indexes are 0-based.charAt/substringthrowStringIndexOutOfBoundsExceptionif the index is invalid. length()is a method onString(arrays use alengthfield).
| Method | What it does | Example on "Java" | Result |
|---|---|---|---|
length() | Number of chars | s.length() | 4 |
isEmpty() | true if length is 0 | "".isEmpty() | true |
isBlank() | Empty or only Unicode whitespace (Java 11) | " ".isBlank() | true |
charAt(i) | Char at index i | s.charAt(0) | J |
toCharArray() | Copy into a char[] | s.toCharArray() | [J, a, v, a] |
getBytes() | Encode to byte[] | s.getBytes() | Platform / UTF-8 bytes |
codePointAt(i) | Unicode code point at i | s.codePointAt(0) | 74 (J) |
indexOf(str) / indexOf(ch) | First index, or -1 | s.indexOf("av") | 1 |
lastIndexOf(str) | Last index, or -1 | s.lastIndexOf("a") | 3 |
contains(seq) | True if substring exists | s.contains("av") | true |
startsWith(prefix) | Prefix check | s.startsWith("Ja") | true |
endsWith(suffix) | Suffix check | s.endsWith("va") | true |
matches(regex) | Whole-string regex match | s.matches("J.*") | true |
regionMatches(i, t, j, len) | Compare a slice | s.regionMatches(1, "ave", 0, 2) | true (av) |
String built-in methods — extract, transform, compare
- Every “change” returns a new
String. The receiver stays the same. substring(begin, end)— begin inclusive, end exclusive.splittakes a regex, not a plain comma unless you quote it.
| Method | What it does | Example | Result |
|---|---|---|---|
substring(i) | From i to the end | "Java".substring(1) | "ava" |
substring(i, j) | From i inclusive to j exclusive | "Java".substring(1, 4) | "ava" |
subSequence(i, j) | CharSequence slice | "Java".subSequence(0, 2) | "Ja" |
split(regex) | Break into String[] | "a,b,c".split(",") | ["a","b","c"] |
concat(t) | Join two strings (prefer +) | "Ja".concat("va") | "Java" |
repeat(n) | Repeat n times (Java 11) | "ab".repeat(3) | "ababab" |
replace(old, neu) | Replace every literal char/CharSequence | "aa".replace("a", "b") | "bb" |
replaceAll(regex, neu) | Replace every regex match | "a1b2".replaceAll("\\d", "-") | "a-b-" |
replaceFirst(regex, neu) | Replace first regex match | "a1b2".replaceFirst("\\d", "-") | "a-b2" |
toLowerCase() / toUpperCase() | New case-converted string | "Java".toUpperCase() | "JAVA" |
trim() | Strip chars ≤ U+0020 from both ends | " x ".trim() | "x" |
strip() | Unicode whitespace (Java 11) | " x ".strip() | "x" |
stripLeading() / stripTrailing() | One side only (Java 11) | " x ".stripLeading() | "x " |
equals(t) | Content equality | "Java".equals("java") | false |
equalsIgnoreCase(t) | Content, ignore case | "Java".equalsIgnoreCase("java") | true |
compareTo(t) | Lexicographic (<0 / 0 / >0) | "A".compareTo("B") | negative |
compareToIgnoreCase(t) | Lexicographic, ignore case | "a".compareToIgnoreCase("A") | 0 |
contentEquals(cs) | Equals any CharSequence / StringBuffer | "ab".contentEquals(sb) | true/false |
String built-in methods — static, encoding, Java 11+
- Static helpers live on the class:
String.valueOf,String.format,String.join. Java 11–15 addedisBlank,lines,repeat,formatted, text blocks.
| Method | Kind | What it does | Example |
|---|---|---|---|
String.valueOf(x) | Static | Any value → String | String.valueOf(42) → "42" |
String.format(fmt, …) | Static | printf-style format | String.format("%02d", 7) → "07" |
s.formatted(…) | Instance (15) | Same as format on this string | "%s-%d".formatted("A", 1) |
String.join(delim, items) | Static | Join pieces | String.join("-", "a", "b") → "a-b" |
intern() | Instance | Return pooled instance | s.intern() == "hi" may be true |
hashCode() | Instance | Cached content hash | Used by HashMap keys |
lines() | Instance (11) | Stream<String> of lines | "a\nb".lines() |
indent(n) | Instance (12) | Add/remove leading spaces | s.indent(2) |
stripIndent() | Instance (15) | Incidental indent out of a block | Text-block helper |
translateEscapes() | Instance (15) | Turn \n in the text into a newline | Unescape a raw string |
toString() | Instance | Returns this string | s.toString() is s |
chars() / codePoints() | Instance | IntStream of chars / code points | Stream pipelines |
getBytes(charset) | Instance | Encode with a charset | s.getBytes(StandardCharsets.UTF_8) |
Differences between String, StringBuffer, and StringBuilder
Stringis immutable.StringBuilderandStringBufferare mutable character sequences injava.lang.- Prefer
StringBuilderfor building text in one thread.StringBufferis the older synchronized twin — rarely needed now.
| Point | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutable? | No | Yes | Yes |
| Thread-safe? | Yes (immutable) | Yes (synchronized methods) | No |
| Speed | Slow if you + in a loop | Slower than Builder (locks) | Fastest mutable builder |
| Storage | New object on every “change” | One buffer, grows as needed | One buffer, grows as needed |
| Package | java.lang.String | java.lang.StringBuffer | java.lang.StringBuilder |
| Since | JDK 1.0 | JDK 1.0 | JDK 1.5 |
| Parent idea | Immutable CharSequence | Synchronized AbstractStringBuilder | Unsynchronized AbstractStringBuilder |
+ concatenation | Creates new Strings | Not used with + | javac often uses this for + |
| Typical methods | charAt, substring, equals | append, insert, delete, reverse | Same API as Buffer |
Return of append | N/A (use concat / +) | this (fluent) | this (fluent) |
| HashMap key? | Yes (stable hashCode) | Avoid (content can change) | Avoid (content can change) |
| When to use | Names, messages, APIs, map keys | Legacy shared builder across threads | Default for loops / building text |
StringBuilder / StringBuffer built-in methods
StringBuilderandStringBuffershare the same method names. Buffer’s versions aresynchronized. Convert back withtoString().
| Method | What it does | Example | Notes |
|---|---|---|---|
append(x) | Add text / number / char at the end | sb.append("Hi").append(3) | Returns this |
insert(i, x) | Insert at index i | sb.insert(0, "Pre") | Shifts the rest |
delete(i, j) | Remove i inclusive to j exclusive | sb.delete(1, 3) | Mutable |
deleteCharAt(i) | Remove one char | sb.deleteCharAt(0) | Mutable |
replace(i, j, str) | Replace a slice | sb.replace(0, 2, "Yo") | Mutable |
reverse() | Reverse in place | new StringBuilder("ab").reverse() | "ba" |
length() | Current character count | sb.length() | Not capacity |
capacity() | Allocated buffer size | sb.capacity() | ≥ length |
ensureCapacity(n) | Grow buffer if needed | sb.ensureCapacity(64) | Fewer reallocations |
setLength(n) | Truncate or pad with NUL | sb.setLength(2) | Shortens or pads |
charAt(i) / setCharAt(i, ch) | Read / overwrite one char | sb.setCharAt(0, ch) | No new object |
indexOf / lastIndexOf | Search inside the buffer | sb.indexOf("a") | -1 if missing |
substring(i, j) | Copy a slice as String | sb.substring(0, 2) | New String |
toString() | Immutable snapshot | sb.toString() | Use this to print / store |
public class BuilderVsString {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" ").append("21").reverse();
System.out.println(sb.toString());
StringBuffer buf = new StringBuffer("OK");
buf.insert(0, "Hi ");
System.out.println(buf);
}
} Advanced — Strings
Concatenation, intern, and complexity
s + tin a loop is O(n²) because each+may copy. javac rewrites a standalone+chain toStringBuilder, but not across a loop. Reuse one builder yourself.intern()returns the pooled instance. Do not intern every runtime string — it can leak heap.StringhashCode is cached. That is why strings make decentHashMapkeys. Never use a liveStringBuilderas a key.trim()only drops characters ≤ U+0020.strip()(Java 11) uses Unicode whitespace (including NBSP).split(".")does not split on a dot —.is regex “any char”. Usesplit("\\.")orPattern.quote.
Text blocks, compact strings, and CharSequence
- Java 9+ compact strings store LATIN-1 in one byte per char when possible. You still write
charAt/codePointAt. - Java 15 text blocks (
""") preserve newlines.stripIndent()andformatted()pair well with them. String,StringBuilder,StringBuffer, andCharBufferall implementCharSequence. APIs often takeCharSequenceso any of them work.contentEqualscompares aStringto aStringBuffer/StringBuilderwithout requiringtoString()first.
public class TextBlockDemo {
public static void main(String[] args) {
String json = """
{"ok": true, "n": %d}
""".formatted(3);
System.out.println(json.strip());
}
} Tricky Interview Points
Q1) Why is String immutable?
Answer Security (paths, class names), thread-safety, string-pool sharing, and a cached hashCode for HashMap 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 in application code.
Q3) String vs StringBuilder vs StringBuffer?
Answer String is immutable. StringBuilder is mutable and not synchronized — default for single-thread building. StringBuffer is mutable and synchronized — older and slower; rarely needed now.
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. Reuse one 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.
Q8) length on String vs array?
Answer String uses the method length(). Arrays use the field length. Collection uses size().
Q9) trim vs strip?
Answer trim removes characters with code point <= 32. strip (Java 11) removes Unicode whitespace. Prefer strip on modern JDKs.
Q10) Does StringBuffer still matter?
Answer Only if an old API requires it or you truly share a builder across threads. New code should use StringBuilder (and a lock / concurrent structure if sharing).
Q11) What does indexOf return when the substring is missing?
Answer -1. contains is a convenience for indexOf(s) >= 0.
Q12) Is String thread-safe?
Answer Yes, because it is immutable — any change is a new object. Sharing a String across threads is safe. Sharing a StringBuilder is not.
Simple Programs
Built-in methods demo
public class StringMethodsDemo {
public static void main(String[] args) {
String s = " Java ";
System.out.println(s.trim().toUpperCase());
System.out.println("Java".substring(1, 4));
System.out.println("a,b,c".split(",")[1]);
System.out.println("ab".repeat(3));
System.out.println(String.join("-", "A", "B"));
}
} 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(',');
}
if (sb.length() > 0) sb.setLength(sb.length() - 1);
System.out.println(sb);
}
} Palindrome ignoring case and spaces
public class Palindrome {
public static void main(String[] args) {
String s = "Never odd or even";
String t = s.toLowerCase().replace(" ", "");
String rev = new StringBuilder(t).reverse().toString();
System.out.println(t.equals(rev));
}
} 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).splittakes a regex:split("\\.")for a real dot.- 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. - Never use
StringBuilderas aHashMapkey — itshashCodechanges as you append. replace(CharSequence, CharSequence)is literal;replaceAllis regex.
Practice Programs List
- Print
length,charAt,indexOf,substring, andtoUpperCasefor"Java". - 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. - Rewrite a
+loop asStringBuilder.appendand compare. - Use
replaceAllto hide digits in a phone-like string. - Compare
trim()vsstrip()on a string that contains a non-breaking space. - Join names with
String.joinand then search withcontains/startsWith. - Use
StringBufferandStringBuildertoappend+reversethe same text; print both.