Java Strings

Work with text in Java: length, charAt, substring, indexOf, replace, split, comparing strings and building text with StringBuilder.

Lesson 15 of 127Beginner18 min read

Text is everywhere in software: names, messages, file paths, web addresses and the contents of documents. In Java, text is stored in String objects. You've already created strings with double quotes and joined them with +. Now you'll learn the methods that let you inspect, search and transform them.

Because String is a class, every string comes with dozens of built-in methods, called with a dot: name.length(), email.contains("@"), title.toUpperCase(). Java strings are also immutable: once created, a string never changes. Methods that seem to modify a string actually return a new one.

In this lesson you'll pick strings apart character by character, search inside them, split them into pieces, compare them correctly and build long text efficiently with StringBuilder. These skills appear in almost every Java program, from form validation to file processing.

Length, characters and substrings

Java
String word = "Keyboard";
word.length();        // 8
word.charAt(0);       // 'K'
word.charAt(word.length() - 1);  // 'd'
word.substring(3);    // "board"
word.substring(0, 3); // "Key"
  • Positions start at 0, so the last character is at length() - 1.
  • charAt() returns a single char, not a String.
  • substring(start, end) includes start but not end. With one argument, it runs to the end of the string.
  • Asking for a position that doesn't exist throws a StringIndexOutOfBoundsException.

Searching and changing case

MethodReturns
s.indexOf("a")Position of the first match, or -1
s.lastIndexOf("a")Position of the last match, or -1
s.contains("abc")true if the text appears
s.startsWith("Mr") / s.endsWith(".pdf")true or false
s.toUpperCase() / s.toLowerCase()A changed copy
s.trim() / s.strip()A copy without leading and trailing spaces
s.replace("a", "b")A copy with every match replaced
s.isEmpty() / s.isBlank()Empty, or only spaces

Remember that none of these change s itself. To keep a result, assign it: s = s.trim();.

Splitting and joining

split() cuts a string into an array of pieces wherever a separator appears:

Java
String csv = "red,green,blue";
String[] colours = csv.split(",");   // ["red", "green", "blue"]

String.join(", ", colours) does the opposite and joins an array back into one string. split() actually takes a regular expression, a powerful pattern language, so a few characters such as . and | have special meanings. To split on a full stop, write split("\\."). Splitting on "\\s+" breaks text on any run of spaces, which is ideal for counting words.

Comparing strings

Use equals() to check whether two strings contain the same characters, and equalsIgnoreCase() to ignore capital letters. Never use == for this: == checks whether two variables refer to the same object in memory, which can be false for identical text, especially text typed by a user or read from a file.

compareTo() compares alphabetically. It returns a negative number if the first string comes first, zero if they're equal and a positive number if it comes second, which is what sorting methods use behind the scenes.

Checking for null, empty and blank strings

A String variable can hold three kinds of "nothing", and they behave differently:

ValueisEmpty()isBlank()
""truetrue
" "falsetrue
nullthrows NullPointerExceptionthrows NullPointerException

null means there is no String object at all, so calling any method on it fails. Check for null first, and let || stop early:

Java
if (name == null || name.isBlank()) {
    System.out.println("Please enter a name");
}

When comparing with a fixed piece of text, putting the literal first avoids the problem: "yes".equals(answer) returns false for a null answer, whereas answer.equals("yes") throws.

Handy methods from newer Java versions

Java 11 added several methods that make common tasks one-liners: "ab".repeat(3) gives "ababab", strip() removes leading and trailing whitespace including Unicode spaces, isBlank() checks for whitespace-only text, and lines() splits text into a stream of lines. Java 15 added text blocks, written between triple quotes """, for multi-line text such as JSON or SQL. These are covered with formatting in the next lesson.

Java Strings Syntax

String methods

s.length()
s.charAt(i)
s.substring(start, end)
s.indexOf("x")
s.toUpperCase()   s.trim()   s.replace("a", "b")
String[] parts = s.split(",");
String.join("-", parts)
a.equals(b)   a.equalsIgnoreCase(b)
StringBuilder sb = new StringBuilder();  sb.append("x");  sb.toString();

Java Strings Summary

  • Strings are immutable objects; methods return new strings.
  • length(), charAt(i) and substring(start, end) read parts of a string; indexes start at 0.
  • indexOf, contains, startsWith, replace and trim search and transform text.
  • split() makes an array; String.join() builds a string from one.
  • Compare text with equals(), never ==; use StringBuilder to build text in loops.

Java Strings Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Taking an email address apart

Java
public class Main {
    public static void main(String[] args) {
        String email = "  Maya.Patel@Example.com ";
        String clean = email.trim().toLowerCase();

        int at = clean.indexOf("@");
        String user = clean.substring(0, at);
        String domain = clean.substring(at + 1);

        System.out.println(clean);
        System.out.println("User: " + user);
        System.out.println("Domain: " + domain);
        System.out.println("Valid? " + (at > 0 && domain.contains(".")));
    }
}
Output
maya.patel@example.com
User: maya.patel
Domain: example.com
Valid? true
Line-by-line explanation
  1. Line 4Methods can be chained: trim first, then make it lower case.
  2. Line 6indexOf finds the position of the @ sign.
  3. Lines 7 to 8Everything before the @ is the user name; everything after it is the domain.
  4. Line 13A simple check: something before the @ and a dot in the domain.
Example 2

Counting words and initials

Java
public class Main {
    public static void main(String[] args) {
        String sentence = "the quick   brown fox";
        String[] words = sentence.trim().split("\\s+");

        System.out.println("Words: " + words.length);

        StringBuilder initials = new StringBuilder();
        for (String w : words) {
            initials.append(Character.toUpperCase(w.charAt(0)));
        }
        System.out.println("Initials: " + initials);
        System.out.println(String.join("-", words));
    }
}
Output
Words: 4
Initials: TQBF
the-quick-brown-fox
Line-by-line explanation
  1. Line 4\\s+ splits on any run of spaces, so the extra spaces don't create empty words.
  2. Lines 8 to 11StringBuilder collects one capital letter per word.
  3. Line 13String.join puts the words back together with dashes.
Example 3

Comparing user input safely

Java
public class Main {
    public static void main(String[] args) {
        String stored = "Paris";
        String typed = new String(" paris ").trim();

        System.out.println(typed == stored);
        System.out.println(typed.equals(stored));
        System.out.println(typed.equalsIgnoreCase(stored));
        System.out.println("apple".compareTo("banana") < 0);
    }
}
Output
false
false
true
true
Line-by-line explanation
  1. Line 4new String(...) creates a separate object, just like text typed by a user.
  2. Line 6== compares objects, not text, so it's false.
  3. Line 7equals compares the text, but the capital P differs.
  4. Line 8equalsIgnoreCase ignores the case difference.
  5. Line 9"apple" comes before "banana", so compareTo returns a negative number.

Common Java Strings Mistakes

Comparing strings with ==

Don't
if (answer == "yes") { ... }
Do
if (answer.equals("yes")) { ... }

Expecting a method to change the string

Don't
String name = "  Leo ";
name.trim();
System.out.println("[" + name + "]");   // [  Leo ]
Do
String name = "  Leo ";
name = name.trim();
System.out.println("[" + name + "]");   // [Leo]

Splitting on a special character

Don't
String[] parts = "v1.2.3".split(".");   // empty array
Do
String[] parts = "v1.2.3".split("\\.");  // ["v1", "2", "3"]

In a regular expression, a plain dot means "any character". Escape it with \\.

Java Strings in Real Projects

Strings in Java applications

Web applications validate email addresses and passwords with string methods, servers split each line of a log file to find errors, and Android apps format prices and dates for display with String.format. Large Java programs that produce reports or HTML build their output with StringBuilder for speed.

Java Strings FAQ

Why are strings immutable in Java?

Immutability makes strings safe to share. A string used as a map key, a file name or a password check can't be changed behind your back by another part of the program or another thread. It also lets Java reuse identical string literals in memory. The cost is that every "change" creates a new string, which is why StringBuilder exists.

What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is a changeable buffer for building text efficiently. StringBuffer is an older version of StringBuilder whose methods are synchronised for use by several threads at once, which makes it slower. Use StringBuilder unless you have a specific reason not to.

How do I reverse a string in Java?

The simplest way is new StringBuilder(text).reverse().toString(), which turns "stressed" into "desserts". Writing your own loop from the last character down to the first is good practice, and it's a common interview question.

How do I sort strings alphabetically?

compareTo() compares two strings by character codes, so all capital letters sort before lowercase letters. For a list, call Collections.sort(list) or list.sort(String.CASE_INSENSITIVE_ORDER) to ignore case. Sorting by the rules of a specific language uses java.text.Collator.

Why does == sometimes work for comparing strings?

String literals with the same text are stored once and shared, so "hi" == "hi" happens to be true. Strings built at run time, read from input or created with new are separate objects, so == returns false even when the text matches. Because the result depends on how a string was created, always use equals().

Java Strings Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints the number of characters in city.

String city = "Lisbon";
System.out.println(city.());
Predict the outputeasy

What does this print?

System.out.println("Computer".substring(3, 6));
Predict the outputmedium

What does this print?

String s = "banana";
System.out.println(s.indexOf("an") + " " + s.lastIndexOf("an"));
Multiple choicemedium

Which line correctly checks whether color holds the text "red", ignoring case?

Predict the outputhard

What does this print?

String[] parts = "a,b,,c".split(",");
System.out.println(parts.length);

Java Strings Quiz

5 questions to check what you learned.

  1. What index does the first character of a Java String have?

    • 1
    • 0
    • -1
    • It depends on the length
  2. What does it mean that strings are immutable?

    • They can't be printed
    • They can only hold letters
    • They can't be compared
    • Once created they never change; methods return new strings
  3. What does "hello".charAt(1) return?

    • 'e'
    • "h"
    • "e"
    • 'h'
  4. When should you use StringBuilder?

    • For every string
    • When comparing strings
    • When building a string from many pieces, for example in a loop
    • When splitting text
  5. What does "Zoo".compareTo("apple") return?

    • A negative number, because capital letters sort before lower-case ones
    • 0
    • A positive number
    • An error