2.7. String Methods

A string holds characters in a sequence. Each character is at a position or index which starts with 0 as shown below. An index is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14.

a string with the position (index) shown above each character

Figure 1: A string with the position (index) shown above each character

Note

The first character in a string is at index 0 and the last characters is at length - 1.

The String class which is built into the default java.lang library simplifies a lot of complex programming tasks for us. Classes are grouped together into a package like java.lang. Many other useful library packages can be imported in. Programmers provide Application Program Interfaces (APIs) to allow other programmers to use their code. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class.

The String class has many useful methods that you can view in the Java String API. This unit explores a few of the methods.

2.7.1. String Methods: length, substring, indexOf

Run the code below to see the output from the String methods length, substring, and indexOf. The length method returns the number of characters in the string, not the last index which is length-1. The str.substring(from,to) method returns the substring from the from index up to (but not including) the to index. The method str.indexOf(substring) returns the index of where it finds substring in str or -1 if it is not there.

This code shows the output from String methods length, substring, and indexOf. How many letters does substring(0,3) return? What does indexOf return when its argument is not found?

Note

Remember that substring(from,to) does not include the character at the to index! To return a single character at index i, use str.substring(index, index + 1).

exercise Check your understanding

2.7.2. CompareTo and Equals

We can compare primitive types like int and double using operators like == and < or >, which you will learn about in the next unit. However, with reference types like String, you must use the methods equals and compareTo, not == or < or >.

The method compareTo compares two strings character by character. If they are equal, it returns 0. If the first string is alphabetically ordered before the second string (which is the argument of compareTo), it returns a negative number. And if the first string is alphabetically ordered after the second string, it returns a positive number. (The actual number that it returns does not matter, but it is the distance in the first letter that is different, e.g. A is 7 letters away from H.)

compareTo

Figure 2: compareTo returns a negative or positive value or 0 based on alphabetical order

The equals method compares the two strings character by character and returns true or false. Both compareTo and equals are case-sensitive. There are case-insensitive versions of these methods, compareToIgnoreCase and equalsIgnoreCase.

Run the example below to see the output from compareTo and equals. Since “Hello!” would be alphabetically ordered after “And”, compareTo returns a positive number. Since “Hello!” would be alphabetically ordered before “Zoo”, compareTo returns a negative number. Notice that equals is case-sensitive.

Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number?

Note

Strings are immutable which means that they can’t change. Anything that you do to modify a string (like creating a substring or appending strings) returns a new string.

exercise Check your understanding

2.7.3. Common Mistakes with Strings

The following code shows some common mistakes with strings.

This code contains some common mistakes with strings. Fix the code to use the string methods correctly.

Here is a list of common mistakes made with Strings.

  • Thinking that substrings include the character at the last index when they don’t.

  • Thinking that strings can change when they can’t. They are immutable.

  • Trying to access part of a string that is not between index 0 and length - 1. This will throw an IndexOutOfBoundsException.

  • Trying to call a method like indexOf on a string reference that is null. You will get a null pointer exception.

  • Using == to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use equals or compareTo instead.

  • Treating upper and lower case characters the same in Java. If s1 = "Hi" and s2 = "hi" then s1.equals(s2) is false.

2.7.4. Summary

  • index - A number that represents the position of a character in a string. The first character in a string is at index 0.

  • length - The number of characters in a string.

  • substring - A new string that contains a copy of part of the original string.

  • A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.

  • String objects are immutable, meaning that String methods do not change the String object. Any method that seems to change a string actually creates a new string.

  • The following String methods and constructors are used in many programs:

    • String(String str) : Constructs a new String object that represents the same sequence of characters as str.

    • int length() : returns the number of characters in a String object.

    • String substring(int from, int to) : returns the substring beginning at index from and ending at index (to – 1).

    • String substring(int from) : returns substring(from, length()).

    • int indexOf(String str) : returns the index of the first occurrence of str; returns -1 if not found.

    • boolean equals(String other) : returns true if this (the calling object) is equal to other; returns false otherwise.

    • int compareTo(String other) : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other.

    • str.substring(index, index + 1) returns a single character at index in string str.

You have attempted of activities on this page