Java Strings: Immutability, Common Methods and StringBuilder

admin5 min read
In this tutorial
  1. Creating strings
  2. Strings are immutable
  3. The string pool, == and equals()
  4. 15 String methods you will use every week
  5. Formatting strings
  6. Text blocks for multi-line strings
  7. StringBuilder for building strings
  8. Converting to and from strings
  9. Common mistakes
  10. Practice
  11. Summary

Almost every program handles text: names, emails, messages, JSON, file paths. In Java, text is represented by the String class, and it behaves a little differently from other objects. Understanding those differences will save you from slow code and confusing bugs.

Creating strings

String greeting = "Hello";            // string literal
String copy = new String("Hello");    // explicit object (rarely needed)
String empty = "";
char[] letters = {'J', 'a', 'v', 'a'};
String fromChars = new String(letters); // "Java"

Prefer literals. They are shorter and let Java reuse objects through the string pool.

Strings are immutable

Once a String object is created, its contents can never change. Methods that look like they modify a string actually return a new string:

String name = "kooredev";
name.toUpperCase();          // result is thrown away
System.out.println(name);    // kooredev

name = name.toUpperCase();   // keep the new string
System.out.println(name);    // KOOREDEV

Immutability makes strings safe to share between threads, safe to use as HashMap keys and safe to cache. The cost is that building a string piece by piece creates many temporary objects, which is why StringBuilder exists (see below).

The string pool, == and equals()

Java keeps a pool of string literals. Two identical literals point to the same pooled object, but strings created at runtime usually do not:

String a = "java";
String b = "java";
String c = new String("java");

System.out.println(a == b);       // true  (same pooled object)
System.out.println(a == c);       // false (different objects)
System.out.println(a.equals(c));  // true  (same characters)

The rule is simple: always compare strings with equals(), or equalsIgnoreCase() when case does not matter. == only tells you whether two references point to the same object, and code that relies on it will break unpredictably.

A null-safe trick: put the literal first. "admin".equals(role) returns false when role is null instead of throwing.

15 String methods you will use every week

public class StringMethods {
    public static void main(String[] args) {
        String s = "  Learn Java at Kooredev  ";

        System.out.println(s.length());                 // 26
        System.out.println(s.strip());                  // "Learn Java at Kooredev"
        String t = s.strip();
        System.out.println(t.toUpperCase());            // LEARN JAVA AT KOOREDEV
        System.out.println(t.toLowerCase());            // learn java at kooredev
        System.out.println(t.charAt(6));                // J
        System.out.println(t.indexOf("Java"));          // 6
        System.out.println(t.contains("Java"));         // true
        System.out.println(t.startsWith("Learn"));      // true
        System.out.println(t.endsWith("dev"));          // true
        System.out.println(t.substring(6, 10));         // Java
        System.out.println(t.replace("Java", "Spring"));// Learn Spring at Kooredev
        System.out.println(String.join("|", t.split(" "))); // Learn|Java|at|Kooredev
        System.out.println("".isEmpty());               // true
        System.out.println("   ".isBlank());            // true
        System.out.println("ab".repeat(3));             // ababab
    }
}

A few notes:

  • substring(begin, end) includes begin and excludes end.
  • strip() (Java 11+) is Unicode-aware; the older trim() only removes ASCII whitespace.
  • split takes a regular expression. To split on a dot, write split("\\."), not split(".").
  • isBlank() returns true for strings that contain only whitespace; isEmpty() only for length 0.

Formatting strings

Concatenating with + gets messy fast. String.format and formatted (Java 15+) are cleaner:

String name = "Ada";
int score = 92;
double avg = 78.456;

String line = String.format("%s scored %d (class average %.1f)", name, score, avg);
String same = "%s scored %d (class average %.1f)".formatted(name, score, avg);
System.out.println(line); // Ada scored 92 (class average 78.5)

Common format specifiers: %s string, %d integer, %.2f decimal with 2 places, %,d thousands separator, %n new line.

Text blocks for multi-line strings

Since Java 15, text blocks make multi-line strings such as JSON or SQL readable:

String json = """
        {
          "name": "Ada",
          "course": "Java Basics"
        }
        """;

Java strips the common indentation, so the text lines up with your code without extra spaces in the result.

StringBuilder for building strings

Because strings are immutable, this loop creates a brand-new string on every iteration:

String result = "";
for (int i = 0; i < 10_000; i++) {
    result += i + ",";   // copies the whole string each time
}

For large loops, that is slow and wasteful. StringBuilder is a mutable buffer designed for exactly this job:

public class BuildCsv {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) {
                sb.append(',');
            }
        }
        System.out.println(sb);            // 1,2,3,4,5

        sb.insert(0, "[").append("]");
        System.out.println(sb);            // [1,2,3,4,5]

        System.out.println(new StringBuilder("level").reverse()); // level
        String finalText = sb.toString();
        System.out.println(finalText.length()); // 11
    }
}

Rules of thumb:

  • A few + concatenations on one line are fine; the compiler optimises them.
  • Building a string inside a loop? Use StringBuilder.
  • StringBuffer is an older, synchronised version. You almost never need it.

Converting to and from strings

int n = Integer.parseInt("42");          // String -> int
double d = Double.parseDouble("3.14");   // String -> double
String s1 = String.valueOf(42);          // int -> String
String s2 = Integer.toString(255, 16);   // "ff" (base 16)
char[] chars = "abc".toCharArray();      // String -> char[]

Integer.parseInt("12a") throws a NumberFormatException, so validate or catch it when parsing user input.

Common mistakes

  • Comparing with == instead of equals().
  • Forgetting that methods return new strings: name.trim(); on its own does nothing.
  • Calling methods on a null string. Check for null or use Objects.requireNonNullElse(s, "").
  • Splitting on a regex special character (., |, *) without escaping it.
  • Building long strings with += in a loop.

Practice

  1. Count the vowels in a sentence.
  2. Capitalise the first letter of every word in a sentence.
  3. Check whether a string is a palindrome. Compare your answer with our five ways to check a palindrome.

Summary

  • Strings are immutable; every “change” returns a new string.
  • Compare text with equals(), never ==.
  • Learn the everyday methods: length, substring, indexOf, split, replace, strip, isBlank.
  • Use String.format or formatted for readable output, and text blocks for multi-line text.
  • Use StringBuilder when you build strings in a loop.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *