Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 24: String Methods and StringBuilder in Java

Java for Beginners · Module 5: Data and Methods


🎯 Working With Text

Lesson 23 showed what a String is. This lesson shows what you can do with one: search it, cut it, change its case, split it into words. Because Strings never change, every one of these methods gives back a new value. When you need to build or edit text repeatedly, StringBuilder is the better tool.

📌 String methods return new Strings and leave the original untouched. StringBuilder is a changeable text buffer that is fast for repeated edits.

1️⃣ The Everyday String Methods

MethodWhat it doesExampleResult
length()number of characters"Java".length()4
charAt(i)character at index i"Java".charAt(2)v
indexOf(x)first position, or -1"Java".indexOf('a')1
substring(a, b)part from a up to b"Java".substring(1, 3)av
toUpperCase()capital letters"Java".toUpperCase()JAVA
trim()removes spaces at both ends" hi ".trim()hi
replace(a, b)swaps text"Java".replace('a', 'o')Jovo
contains(x)true if x occurs inside"Java".contains("av")true
split(sep)cuts into an array"a,b".split(",")[“a”, “b”]

Figure 2: The String methods you will use most.

J
0
a
1
v
2
a
3
␣
4
P
5
r
6
o
7
g
8
r
9
a
10
m
11
m
12
i
13
n
14
g
15
substring(5) = “Programming” (from index 5 to the end). substring(0, 4) = “Java” (index 0 up to, but not including, index 4).

Figure 1: How substring uses indexes.

Program 1: A tour of the methods

public class StringMethods {
    public static void main(String[] args) {
        String s = "  Java Programming  ";
        System.out.println("[" + s + "]");
        System.out.println("trim        : [" + s.trim() + "]");
        String t = s.trim();
        System.out.println("upper       : " + t.toUpperCase());
        System.out.println("lower       : " + t.toLowerCase());
        System.out.println("length      : " + t.length());
        System.out.println("charAt(5)   : " + t.charAt(5));
        System.out.println("indexOf(a)  : " + t.indexOf('a'));
        System.out.println("lastIndexOf : " + t.lastIndexOf('a'));
        System.out.println("indexOf(xyz): " + t.indexOf("xyz"));
        System.out.println("substring(5): " + t.substring(5));
        System.out.println("substring(0,4): " + t.substring(0, 4));
        System.out.println("contains    : " + t.contains("gram"));
        System.out.println("startsWith  : " + t.startsWith("Java"));
        System.out.println("endsWith    : " + t.endsWith("ing"));
        System.out.println("replace     : " + t.replace('a', '@'));
        System.out.println("isEmpty     : " + "".isEmpty());
        System.out.println("isBlank     : " + "   ".isBlank());
        System.out.println("repeat      : " + "ab".repeat(3));
    }
}
🖥️ Output:
[ Java Programming ]
trim : [Java Programming]
upper : JAVA PROGRAMMING
lower : java programming
length : 16
charAt(5) : P
indexOf(a) : 1
lastIndexOf : 10
indexOf(xyz): -1
substring(5): Programming
substring(0,4): Java
contains : true
startsWith : true
endsWith : true
replace : J@v@ Progr@mming
isEmpty : true
isBlank : true
repeat : ababab
  • Square brackets in the output show where the spaces were removed by trim().
  • indexOf returns the first position of a character or text, and -1 if it is not found. lastIndexOf searches from the end.
  • substring(begin, end) includes begin but excludes end. substring(5) runs to the end.
  • replace replaces every occurrence, not just the first.
  • isEmpty() is true only for length 0. isBlank() is also true for spaces only.
  • Every call here returned a new String. The variable t itself never changed.

2️⃣ Splitting, Joining and Converting

import java.util.Arrays;

public class SplitJoin {
    public static void main(String[] args) {
        String line = "Ajay,Rahul,Priya,Sana";
        String[] names = line.split(",");
        System.out.println("count = " + names.length);
        System.out.println(Arrays.toString(names));

        String sentence = "Learning   Java is fun";
        String[] words = sentence.split("\\s+");
        System.out.println(Arrays.toString(words));

        System.out.println(String.join("-", names));
        char[] chars = "hello".toCharArray();
        Arrays.sort(chars);
        System.out.println(new String(chars));
        System.out.println(String.valueOf(3.5) + String.valueOf(true));
        System.out.println(String.format("%s scored %d (%.1f%%)", "Ajay", 87, 87.0));
    }
}
🖥️ Output:
count = 4
[Ajay, Rahul, Priya, Sana]
[Learning, Java, is, fun]
Ajay-Rahul-Priya-Sana
ehllo
3.5true
Ajay scored 87 (87.0%)
  • split(",") cuts a String at every comma and returns an array (Lesson 21).
  • "\\s+" means “one or more spaces”. In Java source the backslash is doubled (Lesson 11). It handles the extra spaces in the sentence.
  • String.join glues an array back together with a separator.
  • toCharArray() turns a String into a char[]. Sorting the characters of “hello” gives “ehllo”, which is a useful step in anagram checks.
  • String.valueOf(...) turns any value into a String (Lesson 9).
  • String.format builds text from a pattern: %s for text, %d for an int, %.1f for one decimal place, and %% for a percent sign.

3️⃣ Putting Methods Together

public class Utility {
    public static void main(String[] args) {
        String text = "Madam";
        String rev = "";
        for (int i = text.length() - 1; i >= 0; i--) {
            rev += text.charAt(i);
        }
        System.out.println("reverse = " + rev);
        System.out.println("palindrome = " + text.equalsIgnoreCase(rev));

        String sentence = "Java is a popular language";
        int vowels = 0;
        for (char c : sentence.toLowerCase().toCharArray()) {
            if ("aeiou".indexOf(c) >= 0) vowels++;
        }
        System.out.println("vowels = " + vowels);
        System.out.println("words  = " + sentence.split(" ").length);
    }
}
🖥️ Output:
reverse = madaM
palindrome = true
vowels = 11
words = 5
  • Reversing walks the String from the last index down to 0 and builds the answer one character at a time.
  • equalsIgnoreCase makes the palindrome check ignore capitals: “Madam” and “madaM” match.
  • Vowel counting uses a neat trick: "aeiou".indexOf(c) is 0 or more only when c is a vowel.

4️⃣ StringBuilder: Text You Can Edit

StringStringBuilder
Changeable?No (immutable)Yes (mutable)
Each changecreates a new objectedits the same object
Joining in a loopslowfast
Thread-safe?Yes (cannot change)No (use StringBuffer if needed)
Use forfixed text, keys, comparisonsbuilding or editing text

Figure 3: String versus StringBuilder.

Joining Strings with += in a loop makes a new String each time. StringBuilder keeps one buffer and edits it in place.

public class SbDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.append(" is").append(" fun");
        System.out.println(sb);
        sb.insert(0, ">> ");
        System.out.println(sb);
        sb.replace(3, 7, "JAVA");
        System.out.println(sb);
        sb.delete(0, 3);
        System.out.println(sb);
        sb.reverse();
        System.out.println(sb);
        sb.setLength(4);
        System.out.println(sb + " | length = " + sb.length());
        String result = sb.toString();
        System.out.println(result.toUpperCase());
    }
}
🖥️ Output:
Java is fun
>> Java is fun
>> JAVA is fun
JAVA is fun
nuf si AVAJ
nuf | length = 4
NUF
  • append adds at the end and returns the same builder, so calls can be chained: sb.append(" is").append(" fun").
  • insert(index, text), replace(start, end, text), delete(start, end) and reverse() all change the same object.
  • setLength(4) cuts the content to 4 characters.
  • When you need a normal String (to compare it, for example), call toString().

Program 5: Why it matters: speed

public class Speed {
    public static void main(String[] args) {
        int n = 50000;

        long t1 = System.nanoTime();
        String s = "";
        for (int i = 0; i < n; i++) {
            s += "x";
        }
        long stringMs = (System.nanoTime() - t1) / 1_000_000;

        long t2 = System.nanoTime();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append("x");
        }
        long sbMs = (System.nanoTime() - t2) / 1_000_000;

        System.out.println("lengths equal: " + (s.length() == sb.length()));
        System.out.println("String += took ms : " + stringMs);
        System.out.println("StringBuilder ms  : " + sbMs);
    }
}
🖥️ Output from one real run (your times will differ):
lengths equal: true
String += took ms : 268
StringBuilder ms : 1
  • Both loops build the same 50,000-character text. The String loop created 50,000 temporary Strings and was hundreds of times slower here.
  • The exact numbers depend on the computer and change every run. The gap is what matters: use StringBuilder when you build text in a loop.
  • Java also has StringBuffer, the older, thread-safe twin of StringBuilder. Prefer StringBuilder in ordinary programs.

5️⃣ Errors Beginners Meet

String and StringBuilder are different types

public class Bad1 {
    public static void main(String[] args) {
        String s = "Java";
        StringBuilder sb = "Java";
        String t = new StringBuilder("x");
    }
}
🖥️ Compiler message:
Bad1.java:4: error: incompatible types: String cannot be converted to StringBuilder
StringBuilder sb = “Java”;
^
Bad1.java:5: error: incompatible types: StringBuilder cannot be converted to String
String t = new StringBuilder(“x”);
^
2 errors
  • Create a builder with new StringBuilder("Java"), and convert back with toString().

substring beyond the end

public class Sub {
    public static void main(String[] args) {
        String s = "Java";
        System.out.println(s.substring(2, 9));
    }
}
🖥️ Runtime error (trimmed):
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: Range [2, 9) out of bounds for length 4
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
… (several internal lines)
at java.base/java.lang.String.substring(String.java:2823)
at Sub.main(Sub.java:4)
  • The end index cannot be larger than length(). The first line says exactly which range was wrong.

⚠️ Common Mistakes

MistakeProblemFix
s.trim(); without storingResult is thrown aways = s.trim();
Thinking substring(0, 4) includes index 4End index is excludedRemember: begin included, end excluded
Forgetting indexOf returns -1Using -1 as an index crashesCheck != -1 first
Comparing sb == "text"Different typessb.toString().equals("text")
Joining Strings in a big loop with +=Very slowUse StringBuilder
Single backslash in split("\s")Invalid escapeDouble it: "\\s"

❓ Frequently Asked Questions

Q1. How do I change one character inside a String?
You cannot. Use replace, build a new String, or use a StringBuilder with setCharAt.

Q2. What is the difference between replace and replaceAll?
replace works on plain text. replaceAll treats the first argument as a pattern (a regular expression).

Q3. How do I compare two StringBuilders?
Not with equals, which compares references. Compare sb1.toString().equals(sb2.toString()).

Q4. Is split(“,”) safe for special characters?
Characters like . and | have special meaning in patterns, so escape them: split("\\.").

✅ Key Takeaways

  • String methods (length, charAt, indexOf, substring, replace, trim, toUpperCase, split) return new values and never change the original.
  • substring(begin, end) excludes end. indexOf returns -1 when nothing is found.
  • String.join, valueOf, format and toCharArray convert between Strings, arrays and values.
  • StringBuilder is mutable: append, insert, delete, reverse. Use it to build text in loops.
  • Call toString() to get a String from a builder.
🎓 Practice questions: (1) Count how many times a given letter appears in a String. (2) Check whether two Strings are anagrams (use toCharArray and Arrays.sort). (3) Print the first letter of each word in a sentence. (4) Reverse a String using StringBuilder. (5) Explain why s.toUpperCase(); does nothing on its own.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision