Java Strings

Java Strings are objects that hold sequences of characters. They are used everywhere, from names and messages to file contents, so the String class comes with dozens of useful methods.

Common String Methods

public class Main {
    public static void main(String[] args) {
        String s = "  Learn Java Today  ";
        String t = s.strip();
        System.out.println(t);
        System.out.println(t.length());
        System.out.println(t.toUpperCase());
        System.out.println(t.indexOf("Java"));
        System.out.println(t.substring(6, 10));
        System.out.println(t.replace("Today", "Now"));
        System.out.println(t.contains("Java"));
        System.out.println(t.charAt(0));
        System.out.println(String.join("-", t.split(" ")));
    }
}
Learn Java Today
16
LEARN JAVA TODAY
6
Java
Learn Java Now
true
L
Learn-Java-Today

Indexes start at 0. substring(6, 10) returns characters from index 6 up to, but not including, index 10. strip removes whitespace at both ends.

Comparing Strings: equals vs ==

Always compare string content with equals. The == operator checks whether two variables point to the same object, which may be false even when the text is identical.

public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = new String("hello");
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println("HELLO".equalsIgnoreCase(a));
        System.out.println("apple".compareTo("banana") < 0);
    }
}
false
true
true
true

Strings Are Immutable

A String can never change. Methods like toUpperCase return a new String. When you build text in a loop, use StringBuilder, which is mutable and much faster than repeated concatenation.

public class Main {
    public static void main(String[] args) {
        var sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) sb.append(", ");
        }
        sb.insert(0, "[").append("]");
        System.out.println(sb.toString());
        System.out.println(new StringBuilder("level").reverse());
    }
}
[1, 2, 3, 4, 5]
level

Text Blocks

Java 15+ supports text blocks for multi-line strings, written between triple quotes. Indentation common to all lines is removed automatically.

public class Main {
    public static void main(String[] args) {
        String json = """
            {
              "name": "Naeem",
              "role": "developer"
            }
            """;
        System.out.print(json);
        System.out.println("Name: %s".formatted("Naeem"));
    }
}
{
  "name": "Naeem",
  "role": "developer"
}
Name: Naeem

Frequently asked questions

Why should I use equals instead of == for strings in Java?

equals compares the characters, while == compares object references. Two strings with the same text can be different objects, so == may return false.

How do I check if a string is empty in Java?

Use isEmpty() for a length of zero, or isBlank() (Java 11+) to also treat whitespace-only strings as empty. Check for null first if the value could be null.

When should I use StringBuilder in Java?

Use StringBuilder when you build a string piece by piece, especially inside loops. For a few simple concatenations, the + operator is fine.