Strings and Characters

A variable of type char stores one character of the Unicode character set. Each character is represented as an integer. For example, 'A' is represented as 65; '3' is represented as 50. An int cast will convert a char to an int; a char cast will convert an int to its equivalent character. Note that character literals are written in single quotes.

A String object is a sequence of zero or more characters. A String literal includes the characters within double quotes, e.g., "foo", "2 +  2 = 3", etc. Each String literal is a String object in Java and can be assigned to a String variable. This web page covers many of the most useful String methods.

In addition to simply writing a String literal, there are many other ways new String objects get created. StringConstructors.java demonstrates a few of them. The following project file contains this program and the programs described below.

length, charAt and getChars methods

StringMiscellaneous.java demonstrates the length, charAt and getChars methods of the String class. Recall that Strings are objects, so that calling a method on a String s follows the pattern:

s.method(parameters)

The length method returns the number of characters in a String. The charAt method returns the character at a specific index in the String (Strings use zero-based indexing). A common pattern to process each char in a String is:

String foo = "foo is footastic";
for (int i = 0; i < foo.length(); i++) {
    char c = foo.charAt(i);
    // process c
}

Comparing Strings

StringCompare.java demonstrates the equals, equalsIgnoreCase, compareTo and regionMatches methods of the String class. It also demonstrates the behavior of the == operator on Strings.

Use the equals method to test two Strings for equality; do not use the == operator. The == operator will sometimes be true for the same String, but it is likely that two Strings that look the same are actually two different String objects, in which case == will evaluate to false. If you want a case-insensitive test, use the equalsIgnoreCase method.

Use the compareTo method to test whether one String is "less than" or "greater than" another String. The expression foo.compareTo(bar) will return a negative number if foo is less than bar, zero if they are equal, or a positive number if foo is greater. This method is based on comparing the numbers representing the characters. As a result. "Z" is less than "a" because 'Z' maps to 90 and 'a' to 97. The compareToIgnoresCase method is more appropriate if you want "a" to be less than "Z".

StringStartEnd.java demonstrates the startsWith and endsWith methods.

Finding Characters and Strings in String

StringIndexMethods.java demonstrates the indexOf and lastIndexOf methods of the String class.

The indexOf method searches for a character or String and returns the first index where the character/String can be found. This method returns -1 if the character or String is not found. An additional parameter can be used to tell the indexOf method where to start searching. This can be used to find all the indexes where the character/String can be found, for example:

String s = "razzle-dazzle";
char c = 'z';
int index = s.indexOf(c);
while (index != -1) {
    System.out.printf("%c can be found at index %d\n", c, index);
    index = s.indexOf(c, index + 1);
}

The lastIndexOf method is similar, but returns the last index where a character/String can be found. Finding all the indexes in reverse order where a character/String can be found would follow this pattern:

String s = "fuzzy-wuzzy";
char c = 'z';
int index = s.lastIndexOf(c);
while (index != -1) {
    System.out.printf("%c can be found at index %d\n", c, index);
    index = s.lastIndexOf(c, index - 1);
}

Extracting Substrings from Strings

SubString.java demonstrates the substring method of the String class. This method can take one or two integer parameters. The first parameter is the starting index for the substring to be extracted. The second parameter is the ending index for the substring to be extracted; if not specified, the ending index is the length of the String. The substring that is returned includes the starting index and excludes the ending index.

Concatenating Strings and Other String Methods

Strings can be concatenated by using the + operator or by using the concat method, as demonstrated by StringConcatenation.java. The same result would be obtained by substituting s1.concat(s2) with s1 + s2.

StringMiscellaneous2.java demonstrates the replace, toLowerCase, toUpperCase, trim and toCharArray methods. An important feature of Java String methods is that methods like replace and trim do not change the original String; instead, they return the new String that results from the operation.

Conversion to Strings

Every Java class should have a toString method that converts instances of that class to a String representation. For primitive types, the String class has static valueOf methods for converting ints, doubles, and so on to Strings. This is demonstrated by StringValueOf.java. Note that static methods follow the pattern:

class.method(parameters)