Skip to content
elephantoo

Strings & StringBuilder

Lesson 9 of 43 17 min read

String methods, immutability, comparison, formatting, text blocks and fast building with StringBuilder.


Text is everywhere: names, messages, JSON, log lines, user input. In Java, text is represented by the String class. This lesson covers the methods you will use every day, the rules that trip people up (immutability and comparison), formatting, text blocks, and StringBuilder for building strings efficiently.

Creating strings#

Java
String greeting = "Hello";          // string literal (the usual way)
String empty = "";                  // empty string, length 0
String copy = new String("Hello");  // explicit object (rarely needed)
String fromChars = String.valueOf(new char[]{'h', 'i'});

Special characters use escape sequences:

EscapeMeaning
\nnewline
\ttab
\"double quote
\\backslash
\u20B9Unicode character (₹)

Essential String methods#

StringMethods.java
public class StringMethods {
    public static void main(String[] args) {
        String s = "  Elephantoo Learning  ";
        String t = s.strip();                       // remove leading/trailing spaces

        System.out.println("[" + t + "]");
        System.out.println(t.length());
        System.out.println(t.charAt(0));             // first character
        System.out.println(t.indexOf("Learn"));      // -1 if not found
        System.out.println(t.substring(0, 10));      // index 0 up to 9
        System.out.println(t.substring(11));         // from 11 to the end
        System.out.println(t.toUpperCase());
        System.out.println(t.replace("Learning", "Academy"));
        System.out.println(t.contains("phant"));
        System.out.println(t.startsWith("Ele") + " " + t.endsWith("ing"));
        System.out.println("".isEmpty() + " " + "   ".isBlank());
        System.out.println("ab".repeat(3));
        System.out.println(t.lastIndexOf('n'));
    }
}
Output
[Elephantoo Learning]
19
E
11
Elephantoo
Learning
ELEPHANTOO LEARNING
Elephantoo Academy
true
true true
true true
ababab
17

Remember: substring(begin, end) includes begin but excludes end. And charAt or substring with an index outside the string throws StringIndexOutOfBoundsException.

strip() (Java 11) understands all Unicode whitespace; the older trim() removes only ASCII spaces and control characters. Prefer strip(), stripLeading() and stripTrailing() in modern code.

Strings are immutable#

Once created, a String object never changes. Methods that seem to modify it actually return a new string:

Immutable.java
public class Immutable {
    public static void main(String[] args) {
        String name = "java";
        name.toUpperCase();              // result discarded!
        System.out.println(name);

        name = name.toUpperCase();       // keep the new string
        System.out.println(name);
    }
}
Output
java
JAVA

Immutability makes strings safe to share between different parts of a program (and between threads), and lets Java cache and reuse them.

Comparing strings#

Comparing.java
public class Comparing {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");

        System.out.println(a == b);               // true: same pooled literal
        System.out.println(a == c);               // false: different objects
        System.out.println(a.equals(c));          // true: same characters
        System.out.println("Hello".equalsIgnoreCase(a));

        System.out.println("apple".compareTo("banana"));  // negative: apple first
        System.out.println("pear".compareTo("pear"));     // zero: equal
        System.out.println("b".compareTo("a"));           // positive
    }
}
Output
true
false
true
true
-1
0
1

Java keeps string literals in a shared string pool, so identical literals can be the same object, which is why a == b happens to be true. Never rely on that: strings built at runtime (user input, concatenation, file contents) are separate objects. Always compare contents with equals.

compareTo returns a negative number, zero, or a positive number depending on alphabetical (Unicode) order. It is what sorting uses.

Splitting and joining#

SplitJoin.java
import java.util.Arrays;

public class SplitJoin {
    public static void main(String[] args) {
        String csv = "Asha,24,Mumbai";
        String[] parts = csv.split(",");
        System.out.println(Arrays.toString(parts));
        int age = Integer.parseInt(parts[1]);
        System.out.println(age + 1);

        String sentence = "Java   is    fun";
        String[] words = sentence.split("\\s+");   // regex: one or more spaces
        System.out.println(words.length);

        System.out.println(String.join(" | ", words));
        System.out.println(String.join("-", "2026", "09", "30"));
    }
}
Output
[Asha, 24, Mumbai]
25
3
Java | is | fun
2026-09-30

The argument to split is a regular expression. Characters like . and | have special meanings, so to split on a literal dot write split("\\.").

Working with characters#

CharCount.java
public class CharCount {
    public static void main(String[] args) {
        String text = "Hello World 2026!";
        int letters = 0, digits = 0, upper = 0;
        for (char ch : text.toCharArray()) {
            if (Character.isLetter(ch)) letters++;
            if (Character.isDigit(ch)) digits++;
            if (Character.isUpperCase(ch)) upper++;
        }
        System.out.println(letters + " letters, " + digits + " digits, " + upper + " uppercase");

        String word = "level";
        String reversed = new StringBuilder(word).reverse().toString();
        System.out.println(word + " is a palindrome? " + word.equals(reversed));
    }
}
Output
10 letters, 4 digits, 2 uppercase
level is a palindrome? true

Formatting strings#

String.format (or the equivalent instance method formatted, Java 15+) builds text from a template:

Formatting.java
public class Formatting {
    public static void main(String[] args) {
        String name = "Ravi";
        int items = 3;
        double total = 1499.5;

        System.out.println(String.format("%s bought %d items for %.2f", name, items, total));
        System.out.println("%-8s|%5d|".formatted("left", 42));
        System.out.println(String.format("%08.3f", Math.PI));
        System.out.println(String.format("%,d", 12345678));
        System.out.println(String.format("%x %o %e", 255, 8, 12345.678));
        System.out.printf("%b %c %%%n", true, 'Z');
    }
}
Output
Ravi bought 3 items for 1499.50
left    |   42|
0003.142
12,345,678
ff 10 1.234568e+04
true Z %
SpecifierMeaning
%sstring (any object, via toString())
%dinteger
%.2fdecimal with 2 places
%10s, %-10swidth 10, right- or left-aligned
%,dthousands separators
%nplatform-independent newline
%%a literal %

Text blocks (Java 15+)#

For multi-line text such as JSON, SQL or HTML, use a text block delimited by triple quotes:

TextBlock.java
public class TextBlock {
    public static void main(String[] args) {
        String json = """
            {
              "name": "Elephantoo",
              "free": true
            }
            """;
        System.out.print(json);

        String sql = """
            SELECT id, name
            FROM users
            WHERE active = %s
            """.formatted(true);
        System.out.print(sql);
    }
}
Output
{
  "name": "Elephantoo",
  "free": true
}
SELECT id, name
FROM users
WHERE active = true

The opening """ must be followed by a newline. Java removes the common indentation (based on the least-indented line, including the closing """), so you can indent the block naturally with your code. No escaping of " is needed inside.

StringBuilder: building strings efficiently#

Because strings are immutable, s += "x" inside a loop creates a new string on every pass and copies all previous characters. For 100,000 iterations that is a lot of wasted work. StringBuilder is a mutable sequence of characters designed for building text:

Builder.java
public class Builder {
    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.toString());

        StringBuilder edit = new StringBuilder("Hello World");
        edit.insert(5, ",")          // Hello, World
            .replace(7, 12, "Java")  // Hello, Java
            .append('!')             // Hello, Java!
            .reverse();              // !avaJ ,olleH
        System.out.println(edit);
        System.out.println(edit.length());

        edit.reverse().deleteCharAt(edit.length() - 1);
        edit.setCharAt(0, 'J');
        System.out.println(edit);
    }
}
Output
1, 2, 3, 4, 5
!avaJ ,olleH
12
Jello, Java

Most StringBuilder methods return the builder itself, so calls can be chained. Call toString() when you need a real String.

When should you use it?

  • Inside loops that build up text: yes, use StringBuilder.
  • A single expression like "Hi " + name + "!": plain + is fine; the compiler optimises it.
  • StringBuffer is an older, synchronised (thread-safe but slower) version. You rarely need it.

Useful conversions#

Java
String s1 = String.valueOf(3.5);        // "3.5"
String s2 = Integer.toString(42);       // "42"
String s3 = "" + 7;                     // "7" (works, but valueOf is clearer)
int n = Integer.parseInt("123");        // 123
double d = Double.parseDouble("2.5");   // 2.5
char[] chars = "abc".toCharArray();     // ['a', 'b', 'c']
String back = new String(chars);        // "abc"

Integer.parseInt("12a") throws a NumberFormatException; you will learn to handle that in the exceptions lesson.

Common mistakes#

  • Comparing strings with == instead of equals.
  • Ignoring the return value of toUpperCase(), replace(), strip() and friends.
  • Calling methods on a null string, which throws NullPointerException. Check for null or use "literal".equals(variable).
  • Off-by-one errors with substring's exclusive end index.
  • Building large strings with += in a loop.

What's next#

That completes the fundamentals! You can write real procedural programs. Next we enter the world of object-oriented programming, starting with classes and objects.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What does this print? String s = "java"; s.toUpperCase(); System.out.println(s);

  2. 2.What is "Elephantoo".substring(2, 5)?

  3. 3.Why is StringBuilder preferred for building a string inside a large loop?

Finished reading?

Mark this lesson complete to track your progress.