TExcelTAD
Home › Java › Java Strings

Java Strings

A String is a sequence of characters, written between double quotes. Strings are objects, so they come with dozens of useful methods. One important fact shapes how you use them: strings are immutable — once created, a String never changes. Methods like toUpperCase() return a new string.

Length and characters

Characters are numbered from 0. charAt(i) returns the character at index i, and length() returns how many characters there are:

java · try it yourself
class Main {
    public static void main(String[] args) {
        String word = "Espresso";
        System.out.println(word.length());
        System.out.println(word.charAt(0));
        System.out.println(word.charAt(word.length() - 1));
        System.out.println(word.indexOf("s"));       // first match
        System.out.println(word.lastIndexOf("s"));   // last match
        System.out.println(word.indexOf("x"));       // not found
    }
}
8
E
o
1
6
-1

Common methods

Method Returns
toUpperCase() / toLowerCase() the string in upper/lower case
trim() / strip() without leading and trailing whitespace
substring(a, b) characters from index a up to (not including) b
contains(s) true if s occurs inside
startsWith(s) / endsWith(s) whether it begins/ends with s
replace(a, b) a copy with every a replaced by b
split(regex) an array of pieces
isEmpty() / isBlank() length 0 / only whitespace
repeat(n) the string repeated n times
java · try it yourself
class Main {
    public static void main(String[] args) {
        String raw = "  Java Programming  ";
        String clean = raw.strip();
        System.out.println("[" + clean + "]");
        System.out.println(clean.toUpperCase());
        System.out.println(clean.substring(5));
        System.out.println(clean.substring(0, 4));
        System.out.println(clean.contains("gram"));
        System.out.println(clean.replace("a", "4"));
        System.out.println("-".repeat(10));
        String[] parts = "red,green,blue".split(",");
        System.out.println(parts.length + " colours, second is " + parts[1]);
        System.out.println(raw);   // unchanged: strings are immutable
    }
}
[Java Programming]
JAVA PROGRAMMING
Programming
Java
true
J4v4 Progr4mming
----------
3 colours, second is green
  Java Programming  

Concatenation

+ joins strings, and any other value is converted to text automatically. concat and String.join are alternatives:

java · try it yourself
class Main {
    public static void main(String[] args) {
        String first = "Alan";
        String last = "Turing";
        int born = 1912;
        System.out.println(first + " " + last + " (" + born + ")");
        System.out.println(first.concat(last));
        System.out.println(String.join(" | ", "one", "two", "three"));
    }
}
Alan Turing (1912)
AlanTuring
one | two | three

When you build a long string inside a loop, use a StringBuilder; it modifies one buffer instead of creating a new string at every step:

java · try it yourself
class Main {
    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());
        System.out.println(sb.reverse());
    }
}
1, 2, 3, 4, 5
5 ,4 ,3 ,2 ,1

Comparing strings

This is the most important string rule in Java: compare contents with equals, not ==. == checks whether two variables point to the same object, which may be false even when the text is identical.

java · try it yourself
class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = new String("hello");
        System.out.println(a == b);                   // different objects
        System.out.println(a.equals(b));              // same contents
        System.out.println("Hello".equalsIgnoreCase(a));
        System.out.println("apple".compareTo("banana"));  // negative: comes first
    }
}
false
true
true
-1

compareTo returns a negative number, zero or a positive number depending on alphabetical order — useful for sorting.

Tip: Write "yes".equals(answer) instead of answer.equals("yes"): it also works when answer is null.

Test yourself

What does "Coffee".substring(1, 4) return?

  1. Cof
  2. off
  3. offe
  4. ofe

How should you check whether two strings have the same text?

  1. a == b
  2. a.equals(b)
  3. a = b
  4. a.same(b)

After String s = "java"; s.toUpperCase(); what is s?

  1. JAVA
  2. java
  3. Java
  4. null