Skip to content
Educora
Beginner15 min3 / 18

Strings and StringBuilder

Learn to work with text: String methods, comparing strings, formatting and the mutable StringBuilder.

Check yourself
In this lesson you will learn
  • Use String methods to extract, search and transform text
  • Compare strings correctly with equals
  • Build text with String.format and StringBuilder

Usernames, text messages, product descriptions, search queries — a large part of the data that programs work with is text. In Java, text is represented by objects of the String class. In this lesson you will learn to cut, search, compare and efficiently build strings.

String methods

A string is a sequence of characters, and each character has an index. Indexes start at 0: in "Baku", B is at index 0 and u is at index 3. The String class has dozens of ready-made methods, which you call with a dot: text.length().

Java
public class Main {
    public static void main(String[] args) {
        String city = "Baku";
        String country = "Azerbaijan";
        String text = city + ", " + country;
        System.out.println(text);
        System.out.println(text.length());
        System.out.println(text.charAt(0));
        System.out.println(text.toUpperCase());
        System.out.println(text.indexOf("Azer"));
        System.out.println(text.substring(6));
        System.out.println(text.substring(0, 4));
        System.out.println(text.contains("ku"));
        System.out.println(text.replace("Baku", "Ganja"));
        System.out.println("  hello  ".trim() + "!");
    }
}
Expected output
Baku, Azerbaijan
16
B
BAKU, AZERBAIJAN
6
Azerbaijan
Baku
true
Ganja, Azerbaijan
hello!
MethodWhat it doesIn the example
length()returns the number of characters16
charAt(i)the character at index icharAt(0) → B
indexOf(s)where s first starts (−1 if not found)indexOf("Azer") → 6
substring(a, b)the part from a up to, but not including, bsubstring(0, 4) → Baku
toUpperCase(), toLowerCase()converts to upper or lower caseBAKU, AZERBAIJAN
contains(s)whether s occurs in the stringcontains("ku") → true
replace(a, b)replaces every a with bGanja, Azerbaijan
trim()removes spaces at the start and the endhello

Strings are immutable

Once a String object has been created, it cannot be changed — it is immutable. Methods like toUpperCase() do not change the old string; they return a new one. If you want to keep the result, assign it to a variable.

Java
public class Main {
    public static void main(String[] args) {
        String name = "aysel";
        name.toUpperCase();
        System.out.println(name);
        name = name.toUpperCase();
        System.out.println(name);
    }
}
Expected output
aysel
AYSEL

Comparing strings

The == operator does not compare the text of two strings — it checks whether they are the same object in memory. To compare the content, use equals(), and to ignore upper and lower case, use equalsIgnoreCase().

Java
public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = new String("java");
        String c = "JAVA";
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
        System.out.println(a.equalsIgnoreCase(c));
    }
}
Expected output
false
true
false
true

Formatting and joining

When you join many pieces with +, the text quickly becomes hard to read. String.format() takes a template: %s is replaced by a string, %d by an integer, %.1f by a decimal with one digit after the point, and %% prints a percent sign. System.out.printf() prints such a template directly, and %n means a new line.

Java
public class Main {
    public static void main(String[] args) {
        String name = "Elvin";
        int score = 47;
        double percent = 94.0;
        String report = String.format("%s scored %d points (%.1f%%)", name, score, percent);
        System.out.println(report);
        System.out.printf("Price: %.2f AZN%n", 12.5);
        System.out.println("a" + 1 + 2);
        System.out.println(1 + 2 + "a");
    }
}
Expected output
Elvin scored 47 points (94.0%)
Price: 12.50 AZN
a12
3a
The decimal separator depends on the computer's regional settings: with Azerbaijani, Russian or Turkish settings you will see 94,0 and 12,50.

Look at the last two lines: + is evaluated from left to right. "a" + 1 is already a string, so 2 is attached to it as text too. In 1 + 2 + "a" the numbers are added first, and only then is the result joined to the text.

StringBuilder: a mutable string

Because strings are immutable, every + creates a new object. When text is built from hundreds of small pieces (for example, inside a loop), this wastes memory and time. **StringBuilder** is a mutable string: append() adds to the end, insert() puts text anywhere, reverse() flips it, and toString() returns the finished String.

Java
public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(", ");
        sb.append("Elvin").append('!');
        System.out.println(sb);
        sb.insert(0, ">> ");
        System.out.println(sb);
        System.out.println(sb.length());
        sb.reverse();
        System.out.println(sb);
        String word = "level";
        String reversed = new StringBuilder(word).reverse().toString();
        System.out.println(word.equals(reversed));
    }
}
Expected output
Hello, Elvin!
>> Hello, Elvin!
16
!nivlE ,olleH >>
true

The last lines check for a palindrome — a word that reads the same backwards: we reverse level and compare it with the original. Calls can also be chained like append(...).append(...), because each append returns the same StringBuilder.

Key points

  • String indexes start at 0; the last character is at length() - 1.
  • String is immutable: methods like toUpperCase() and replace() return a new string.
  • Compare the content of strings with equals(), not with ==.
  • String.format() and printf() build text from a template: %s, %d, %.2f, %n.
  • StringBuilder is a mutable string: append, insert, reverse, toString.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What does "Java".charAt(1) return?