Skills101

Java Programming · Lesson 5 of 15 · Updated ·

Strings in Java — Immutability, String Pool, equals() and StringBuilder

String is the most used class in Java. Two facts explain most String questions in interviews: strings are immutable, and literals are shared in a string pool.

1. == vs equals() and the string pool

s1 and s2 created from the literal "java" share one object in the string pool, so s1 == s2 is true. s3 created with new String is a different object, so s1 == s3 is false, but s1.equals(s3) is true

public class Main {
    public static void main(String[] args) {
        String s1 = "java";
        String s2 = "java";
        String s3 = new String("java");
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s1.equals(s3));
        System.out.println("JAVA".equalsIgnoreCase(s1));
    }
}
true
false
true
true
  • == checks if two variables point to the same object.
  • .equals() checks if the text is the same. Always use .equals() for strings.

2. Strings are immutable

A String can never change. Methods like toUpperCase() return a new String.

public class Main {
    public static void main(String[] args) {
        String s = "hello";
        s.toUpperCase();          // result thrown away
        System.out.println(s);
        s = s.toUpperCase();      // keep the new string
        System.out.println(s);
    }
}
hello
HELLO

Why immutable? Safety (strings are used for passwords, file paths, class names), the string pool can share them, and they are thread-safe.

3. Most-used methods

public class Main {
    public static void main(String[] args) {
        String t = "  Skills101 Java Course  ".trim();
        System.out.println(t.length());
        System.out.println(t.charAt(0) + " " + t.indexOf("Java") + " " + t.contains("Course"));
        System.out.println(t.substring(10, 14));
        System.out.println(t.replace("Java", "Python"));
        System.out.println(t.toLowerCase().startsWith("skills"));
        String[] parts = "a,b,c".split(",");
        System.out.println(parts.length + " " + String.join("-", parts));
        System.out.println("apple".compareTo("banana") < 0);
    }
}
21
S 10 true
Java
Skills101 Python Course
true
3 a-b-c
true
  • substring(start, end) — end is excluded (like Python slicing).
  • compareTo returns negative / 0 / positive for alphabetical order.

4. StringBuilder: build strings fast

Because Strings are immutable, s = s + x in a loop creates a new object every time. Use StringBuilder instead.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i).append(",");
        }
        sb.setLength(sb.length() - 1);     // remove last comma
        System.out.println(sb);
        System.out.println(new StringBuilder("racecar").reverse());
        sb.insert(0, "[").append("]");
        System.out.println(sb.toString());
    }
}
1,2,3,4,5
racecar
[1,2,3,4,5]
StringStringBuilderStringBuffer
Changeable?noyesyes
Thread-safe?yes (immutable)noyes (synchronized)
Speedslow to modifyfastestslower

5. Interview programs

Palindrome

public class Main {
    static boolean isPalindrome(String s) {
        s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        int l = 0, r = s.length() - 1;
        while (l < r) {
            if (s.charAt(l++) != s.charAt(r--)) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println(isPalindrome("Madam") + " " + isPalindrome("A man, a plan, a canal: Panama") + " " + isPalindrome("Java"));
    }
}
true true false

Count character frequency

public class Main {
    public static void main(String[] args) {
        String s = "programming";
        int[] freq = new int[26];
        for (char c : s.toCharArray()) freq[c - 'a']++;
        for (int i = 0; i < 26; i++) {
            if (freq[i] > 1) System.out.print((char) ('a' + i) + "=" + freq[i] + " ");
        }
        System.out.println();
    }
}
g=2 m=2 r=2

Common mistakes

  • Comparing strings with ==.
  • Calling a method and ignoring the returned new string.
  • Building strings with + inside big loops.

Quick recap

  • == compares references; .equals() compares text.
  • Literals share the string pool; new String makes a new object.
  • Strings are immutable; use StringBuilder to build them.
  • substring(start, end) excludes end.

Practice what you learned

📝 Quiz: Java Strings5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →