Skip to main content

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.

L1

Basics — Strings

Section: Arrays & Strings. String immutability, the string pool, built-in String methods, and String vs StringBuffer vs StringBuilder.

What is a String?

  • String is a class in java.lang, not a primitive. It stores a sequence of characters (Java 9+ compact byte[]: 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.
IdeaMeaningReal-life mapping
CharactersLetters / digits / symbolsLetters in a name
length()How many charactersPassword must be ≥ 8
IndexPosition from 0First letter of a name
Empty string"" — length 0Blank 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 a String with new 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). equals on String tests character content.
  • Call equals on the literal ("OK".equals(s)) so a null s does not throw. Or use Objects.equals(a, b).
Check==equals
What it comparesReference identityValue (for String, content)
"ab" == "a" + "b"Often true (constant fold + intern)Always true if content matches
new String("x") == "x"falsetrue
Nulls == null is safes.equals(...) NPEs if s is null
Use for strings?Almost neverYes — or Objects.equals(a, b)

String built-in methods — inspect and search

  • Call instance methods as s.method(...). Indexes are 0-based. charAt / substring throw StringIndexOutOfBoundsException if the index is invalid.
  • length() is a method on String (arrays use a length field).
MethodWhat it doesExample on "Java"Result
length()Number of charss.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 is.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 is.codePointAt(0)74 (J)
indexOf(str) / indexOf(ch)First index, or -1s.indexOf("av")1
lastIndexOf(str)Last index, or -1s.lastIndexOf("a")3
contains(seq)True if substring existss.contains("av")true
startsWith(prefix)Prefix checks.startsWith("Ja")true
endsWith(suffix)Suffix checks.endsWith("va")true
matches(regex)Whole-string regex matchs.matches("J.*")true
regionMatches(i, t, j, len)Compare a slices.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. split takes a regex, not a plain comma unless you quote it.
MethodWhat it doesExampleResult
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 added isBlank, lines, repeat, formatted, text blocks.
MethodKindWhat it doesExample
String.valueOf(x)StaticAny value → StringString.valueOf(42) → "42"
String.format(fmt, …)Staticprintf-style formatString.format("%02d", 7) → "07"
s.formatted(…)Instance (15)Same as format on this string"%s-%d".formatted("A", 1)
String.join(delim, items)StaticJoin piecesString.join("-", "a", "b") → "a-b"
intern()InstanceReturn pooled instances.intern() == "hi" may be true
hashCode()InstanceCached content hashUsed by HashMap keys
lines()Instance (11)Stream<String> of lines"a\nb".lines()
indent(n)Instance (12)Add/remove leading spacess.indent(2)
stripIndent()Instance (15)Incidental indent out of a blockText-block helper
translateEscapes()Instance (15)Turn \n in the text into a newlineUnescape a raw string
toString()InstanceReturns this strings.toString() is s
chars() / codePoints()InstanceIntStream of chars / code pointsStream pipelines
getBytes(charset)InstanceEncode with a charsets.getBytes(StandardCharsets.UTF_8)

Differences between String, StringBuffer, and StringBuilder

  • String is immutable. StringBuilder and StringBuffer are mutable character sequences in java.lang.
  • Prefer StringBuilder for building text in one thread. StringBuffer is the older synchronized twin — rarely needed now.
PointStringStringBufferStringBuilder
Mutable?NoYesYes
Thread-safe?Yes (immutable)Yes (synchronized methods)No
SpeedSlow if you + in a loopSlower than Builder (locks)Fastest mutable builder
StorageNew object on every “change”One buffer, grows as neededOne buffer, grows as needed
Packagejava.lang.Stringjava.lang.StringBufferjava.lang.StringBuilder
SinceJDK 1.0JDK 1.0JDK 1.5
Parent ideaImmutable CharSequenceSynchronized AbstractStringBuilderUnsynchronized AbstractStringBuilder
+ concatenationCreates new StringsNot used with +javac often uses this for +
Typical methodscharAt, substring, equalsappend, insert, delete, reverseSame API as Buffer
Return of appendN/A (use concat / +)this (fluent)this (fluent)
HashMap key?Yes (stable hashCode)Avoid (content can change)Avoid (content can change)
When to useNames, messages, APIs, map keysLegacy shared builder across threadsDefault for loops / building text

StringBuilder / StringBuffer built-in methods

  • StringBuilder and StringBuffer share the same method names. Buffer’s versions are synchronized. Convert back with toString().
MethodWhat it doesExampleNotes
append(x)Add text / number / char at the endsb.append("Hi").append(3)Returns this
insert(i, x)Insert at index isb.insert(0, "Pre")Shifts the rest
delete(i, j)Remove i inclusive to j exclusivesb.delete(1, 3)Mutable
deleteCharAt(i)Remove one charsb.deleteCharAt(0)Mutable
replace(i, j, str)Replace a slicesb.replace(0, 2, "Yo")Mutable
reverse()Reverse in placenew StringBuilder("ab").reverse()"ba"
length()Current character countsb.length()Not capacity
capacity()Allocated buffer sizesb.capacity()≥ length
ensureCapacity(n)Grow buffer if neededsb.ensureCapacity(64)Fewer reallocations
setLength(n)Truncate or pad with NULsb.setLength(2)Shortens or pads
charAt(i) / setCharAt(i, ch)Read / overwrite one charsb.setCharAt(0, ch)No new object
indexOf / lastIndexOfSearch inside the buffersb.indexOf("a")-1 if missing
substring(i, j)Copy a slice as Stringsb.substring(0, 2)New String
toString()Immutable snapshotsb.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);
    }
}
L2

Advanced — Strings

Concatenation, intern, and complexity

  • s + t in a loop is O(n²) because each + may copy. javac rewrites a standalone + chain to StringBuilder, but not across a loop. Reuse one builder yourself.
  • intern() returns the pooled instance. Do not intern every runtime string — it can leak heap.
  • String hashCode is cached. That is why strings make decent HashMap keys. Never use a live StringBuilder as 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”. Use split("\\.") or Pattern.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() and formatted() pair well with them.
  • String, StringBuilder, StringBuffer, and CharBuffer all implement CharSequence. APIs often take CharSequence so any of them work.
  • contentEquals compares a String to a StringBuffer/StringBuilder without requiring toString() first.
public class TextBlockDemo {
    public static void main(String[] args) {
        String json = """
                {"ok": true, "n": %d}
                """.formatted(3);
        System.out.println(json.strip());
    }
}
L3

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.

L4

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));
    }
}
L5

Problem Solving Tricks

  • Call equals on the literal: "OK".equals(s) never NPEs.
  • Use Objects.equals(a, b) when either side may be null.
  • isEmpty() is length() == 0. isBlank() also treats whitespace as empty (Java 11).
  • split takes 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 StringBuilder as a HashMap key — its hashCode changes as you append.
  • replace(CharSequence, CharSequence) is literal; replaceAll is regex.
L6

Practice Programs List

  1. Print length, charAt, indexOf, substring, and toUpperCase for "Java".
  2. Count vowels and consonants in a line of text.
  3. Check palindrome after ignoring case and spaces.
  4. Implement indexOf yourself for a character.
  5. Split a CSV line and trim each part.
  6. Build the string 1,2,3,...,n with StringBuilder (no trailing comma).
  7. Show three cases where == is true and three where only equals is true.
  8. Rewrite a + loop as StringBuilder.append and compare.
  9. Use replaceAll to hide digits in a phone-like string.
  10. Compare trim() vs strip() on a string that contains a non-breaking space.
  11. Join names with String.join and then search with contains / startsWith.
  12. Use StringBuffer and StringBuilder to append + reverse the same text; print both.