Reading history

Java Strings: Methods, StringBuilder and Formatting

4 min read 0 views

Learn Java strings: common String methods, comparing with equals(), immutability, StringBuilder, String.format() and text blocks.

Text in Java is stored in String objects. Strings are immutable: once created, a string’s characters cannot change, so a call such as toUpperCase() hands back a separate string. Java gives you dozens of methods for searching, cutting, comparing and transforming text, plus StringBuilder for building text efficiently. This lesson covers the ones you will use every day.

In this lesson you will learn

  • The most useful String methods
  • How to compare strings correctly
  • Why strings are immutable
  • How to build text with StringBuilder
  • Formatting with String.format() and text blocks

Everyday String Methods

public class Main {
    public static void main(String[] args) {
        String s = "  Core Tech ED  ";
        String t = s.trim();
        System.out.println("[" + t + "] length " + t.length());
        System.out.println(t.toUpperCase() + " | " + t.toLowerCase());
        System.out.println(t.charAt(0) + " " + t.indexOf("Tech") + " " + t.substring(5, 9));
        System.out.println(t.contains("ED") + " " + t.startsWith("Core"));
        System.out.println(t.replace("ED", "Education"));
        System.out.println(String.join("-", t.split(" ")));
        System.out.println("java".equals("Java") + " " + "java".equalsIgnoreCase("Java"));
    }
}

Output

[Core Tech ED] length 12
CORE TECH ED | core tech ed
C 5 Tech
true true
Core Tech Education
Core-Tech-ED
false true
  • trim() removes spaces at both ends; length() counts characters.
  • charAt(0) reads one character; indexOf("Tech") finds a position (or -1 if missing).
  • substring(5, 9) takes characters 5 to 8. The end index is not included.
  • split(" ") breaks text into an array; String.join("-", parts) glues it back with a separator.
  • equals() is case-sensitive; equalsIgnoreCase() is not.

Strings are immutable

t.toUpperCase() did not change t; it returned a new string. To keep a result, assign it: t = t.toUpperCase();

StringBuilder, format() and Text Blocks

public class Main {
    public static void main(String[] args) {
        String word = "level";
        String reversed = new StringBuilder(word).reverse().toString();
        System.out.println(word + " palindrome? " + word.equals(reversed));

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) sb.append(",");
        }
        System.out.println(sb);

        String report = String.format("%-8s|%6.2f|%03d", "Rafi", 92.456, 7);
        System.out.println(report);

        String text = """
            Line one
            Line two""";                  // text block (Java 15+)
        System.out.println(text.lines().count() + " lines");
    }
}

Output

level palindrome? true
1,2,3,4,5
Rafi    | 92.46|007
2 lines
  • StringBuilder is a mutable string. Use append() in loops instead of +=, which would create a new string on every pass. It also has reverse(), used here to check for a palindrome.
  • String.format() uses format codes: %-8s left-aligns a string in 8 characters, %6.2f prints a decimal with 2 places in 6 characters, and %03d pads an integer with zeros.
  • Text blocks (""", Java 15+) write multi-line strings without \n escapes.

String Methods Reference

MethodReturns
length()Number of characters
charAt(i)Character at index i
indexOf(s) / lastIndexOf(s)First / last position of s, or -1
substring(a, b)Characters from a up to (not including) b
contains(s), startsWith(s), endsWith(s)boolean
replace(a, b)New string with every a replaced
split(regex)String[]
isEmpty() / isBlank()Empty / only whitespace
compareTo(s)Negative, 0 or positive for alphabetical order

Common Mistakes

  1. Comparing with ==. It checks whether two variables point to the same object, not the same text. Use equals().
  2. Ignoring the return value of trim(), replace() and similar methods.
  3. Calling a method on null, which throws NullPointerException. "yes".equals(input) is safe even if input is null.
  4. Building long strings with + in a loop. Use StringBuilder.

Practice Exercises

Exercise 1. Count the vowels in “Programming in Java”.

Show answer
String s = "Programming in Java".toLowerCase();
int count = 0;
for (char c : s.toCharArray()) {
    if ("aeiou".indexOf(c) >= 0) count++;
}
System.out.println(count);   // 6

Exercise 2. Turn “core tech ed” into “Core Tech Ed”.

Show answer
StringBuilder out = new StringBuilder();
for (String w : "core tech ed".split(" ")) {
    out.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1)).append(" ");
}
System.out.println(out.toString().trim());

Frequently Asked Questions

What is the difference between StringBuilder and StringBuffer?

They have the same methods. StringBuffer is synchronised for use by several threads, which makes it slower. Use StringBuilder unless you need thread safety.

Why are Java strings immutable?

Immutability makes strings safe to share between threads, lets Java reuse identical string literals from a pool, and makes them reliable keys in hash maps.

Summary

  • Strings are immutable; methods return new strings.
  • Compare text with equals() or equalsIgnoreCase().
  • StringBuilder builds text efficiently in loops.
  • String.format() and text blocks handle formatting and multi-line text.

Next: Java Methods.

Lessons are also marked complete when you click Next.

Leave a Reply

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