String and its methods

A String is an object, not a primitive and not an array of characters. It is immutable: every method that seems to change it returns a new string and leaves the old one alone. That one rule explains the results of this lesson, including the ones that look like bugs.

A string is an object

A literal such as "Java" is a String object created by the compiler, and String is a final class in java.lang. Its characters are stored inside it, and the class offers methods instead of an index operator: there is no text[0] in Java.

The file Strings.java runs the most common methods on one string with spaces at both ends:

public class Strings { public static void main(String[] args) { String text = " Hello, Java "; System.out.println("length: " + text.length()); System.out.println("strip: [" + text.strip() + "]"); System.out.println("charAt: " + text.charAt(2)); System.out.println("substring: " + text.substring(2, 7)); System.out.println("indexOf: " + text.indexOf("Java")); System.out.println("upper: " + text.toUpperCase()); System.out.println("replace: " + text.replace("Java", "World")); } }

javac -Xlint:all Strings.java
java Strings

length: 15
strip: [Hello, Java]
charAt: H
substring: Hello
indexOf: 9
upper: HELLO, JAVA
replace: Hello, World

The string has 15 characters because the four spaces count, strip removes the spaces at both ends and gives the 11 characters in the brackets, and charAt(2) is the first letter after the two leading spaces. indexOf reports where Java starts in the original string, with the spaces included.

Immutable

toUpperCase and replace do not change the string they are called on; they return a new one. The original keeps its spaces and its case, and the two results above still show the leading spaces because they were only upper-cased and replaced.

public class Immutable { public static void main(String[] args) { String a = "java"; String b = a.toUpperCase(); System.out.println("a: " + a); System.out.println("b: " + b); System.out.println("same object: " + (a == b)); } }

javac -Xlint:all Immutable.java
java Immutable

a: java
b: JAVA
same object: false

Immutability is why a string can be shared freely and used as a map key. It is also why a loop that builds a string with += copies the whole string on every pass, which is the subject of the next lesson.

length, charAt and substring

length() returns the number of UTF-16 code units, so a character outside the basic plane counts twice. charAt(i) returns the code unit at an index, and the valid indices are 0 to length() - 1. substring(from, to) takes the second index as exclusive, exactly like copyOfRange on arrays.

indexOf returns the first position of a substring or -1, and contains is the same question with a boolean answer. strip, stripLeading and stripTrailing remove whitespace by the Unicode definition, which is wider than the ASCII spaces of trim.

equals and compareTo

equals answers whether two strings have the same characters, and compareTo answers how they are ordered. A negative result means the receiver comes first in the dictionary, zero means equal, and a positive result means it comes later.

public class Compare { public static void main(String[] args) { String a = "apple"; String b = "banana"; System.out.println("compareTo: " + a.compareTo(b)); System.out.println("equals: " + a.equals("apple")); System.out.println("ignore: " + a.equalsIgnoreCase("APPLE")); System.out.println("starts: " + b.startsWith("ban")); System.out.println("same: " + a.compareTo("apple")); } }

javac -Xlint:all Compare.java
java Compare

compareTo: -1
equals: true
ignore: true
starts: true
same: 0

The result -1 is not a promise about the exact difference: the method returns the difference of the first pair of characters that differ, and a is one below b. A program should test the sign, not the value. equals and compareTo are the two methods behind sorting and the collections of the next part.

Exercises

  1. Print the last character of a string without writing its index by hand.
  2. Replace every space in the string with an underscore and print the result and the original.
  3. Compare "apple" and "Apple" with compareTo and with compareToIgnoreCase.
  4. Find the second occurrence of a in a word with indexOf and a starting index.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does text.charAt(2) return for " Hello"?

    Answer

    H

    The two leading spaces are indices 0 and 1, so index 2 is the first letter.

  2. What does substring(2, 7) return?

    Answer

    Five characters, from index 2 up to but not including 7

    The first index is inclusive and the second is exclusive, so the length is 7 - 2.

  3. What does compareTo return for two equal strings?

    Answer

    0

    Zero means the strings are equal in the ordering, and the same as equals for strings.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String text = "java"; String upper = text.toUpperCase(); System.out.println(text + " " + upper); } }

    Answer

    java JAVA

    toUpperCase returns a new string and leaves the original at java.

  5. What does this program print? public class Q2 { public static void main(String[] args) { String text = " hello "; System.out.println("[" + text.strip() + "]"); } }

    Answer

    [hello]

    strip removes the spaces at both ends, including the two on each side.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String text = "banana"; System.out.println(text.indexOf("na")); } }

    Answer

    2

    The first na starts at index 2, after ba.

  7. What does this program print? public class Q4 { public static void main(String[] args) { String a = "apple"; String b = "banana"; System.out.println(a.compareTo(b) < 0); } }

    Answer

    true

    apple sorts before banana, so compareTo is negative and the test is true.

  8. What does this program print? public class Q5 { public static void main(String[] args) { String text = "abcdef"; System.out.println(text.substring(1, 4)); } }

    Answer

    bcd

    Indices 1, 2 and 3 are b, c and d; index 4 is excluded.

  9. What does indexOf return when the substring is absent?

    Answer

    -1

    The convention is -1, the same as the array searches of the previous lessons.

  10. Why is a String safe to share between parts of a program?

    Answer

    It is immutable, so no part can change it

    No method changes the characters of an existing string; a change produces a new object.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev