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

Source: https://skills101.in/learn/java/java-strings — Skills101 free tutorial (Java Programming). Updated 2026-11-09.

`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](https://skills101.in/learn-img/java/string-pool.svg)

```java
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));
    }
}
```

```text
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.

```java
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);
    }
}
```

```text
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

```java
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);
    }
}
```

```text
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.

```java
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());
    }
}
```

```text
1,2,3,4,5
racecar
[1,2,3,4,5]
```

| | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Changeable? | no | yes | yes |
| Thread-safe? | yes (immutable) | no | yes (synchronized) |
| Speed | slow to modify | **fastest** | slower |

## 5. Interview programs

### Palindrome

```java
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"));
    }
}
```

```text
true true false
```

### Count character frequency

```java
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();
    }
}
```

```text
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 quiz and free certificate: https://skills101.in/learn/java/java-strings