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, == vs equals, and StringBuilder vs StringBuffer.

String is a class, and it is immutable

  • String lives in java.lang. Once created, its char/byte content never changes. Methods like toUpperCase() 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 in charAt / 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). equals on String tests character content (and is null-safe only if you call it on the non-null side).
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)

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).
  • substring in modern JDKs copies (no shared backing array). Empty string "" has length 0 and is interned.

StringBuilder vs StringBuffer vs String

TypeMutable?Thread-safe?When to use
StringNoYes (immutable)Keys, messages, APIs
StringBuilderYesNoDefault choice for building text in one thread
StringBufferYesYes (synchronized)Legacy shared builders; rarely needed now
L2

Advanced — Strings

Concatenation, intern, and complexity

  • s + t in a loop is O(n²) because each + may copy. The compiler rewrites *standalone* + chains to StringBuilder, but not across a loop. Use StringBuilder yourself.
  • intern() returns the pooled instance. Do not intern every runtime string — it can leak metaspace/heap.
  • String hashCode is cached. That is why strings make decent HashMap keys.
  • Never compare strings with == in application code. Interviews will still ask when == happens to be true.
L3

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.

L4

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());
    }
}
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).
  • 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.
L6

Practice Programs List

  1. Count vowels and consonants in a line of text.
  2. Check palindrome after ignoring case and spaces.
  3. Implement indexOf yourself for a character.
  4. Split a CSV line and trim each part.
  5. Build the string 1,2,3,...,n with StringBuilder (no trailing comma).
  6. Show three cases where == is true and three where only equals is true.