You are on page 1of 6

DATATYPES AND CONTROL STRUCTURES:

The String Class in Java

OVERVIEW:
Strings are an important variable type in Java. We can use them to
receive words and names from the user, as well as addresses and postal
codes. Numbers can be stored in strings, but when this is done, we
usually don't want to perform any calculations with the numbers.

Strings are made up of a series of characters, all attached together.


Characters can include letters, numbers, punctuation and symbols. Even
a space is a character.

Often, when we receive strings from a user, we like to do things with them. It might involve finding out
its length, or the location of a certain character within the string. Other times we like to splice the string
(cut it up) or concatenate it (add it to another string to make one long string).

Fortunately, in Java, subroutines already exist that allow us to do these things to the strings. When we
need to use a string command, we simply type the variable name of the string, add a period, and then
type the command we would like to use. Sometimes, we also have to send some specific information to
the command, like which letter we're searching for, or which characters. The String class includes
numerous methods for manipulating strings.

REFLECTION QUESTION:

Using our prior knowledge from the last unit, if we have the string “Coding Wizard” stored in a variable,
how can we count the number of characters in the string, including the space?

LEARNING GOALS:

• To understand that Strings are text consisting of any symbol on the


keyboard.
• To understand that Java sees “123” and 123 differently.
• To understand the importance of indexing in programming
• To be able to identify the String method(s) needed for a given situation.

The String Class Page 1 of 6


The following is a list of just some of the String methods, with the highlighted ones being the more
commonly used methods:

METHOD DESCRIPTION EXAMPLE

charAt(int index): char Returns the character at the specified index word.charAt(2);

concat(String str): String Concatenates the specified string to the end word.concat(word2);
of this string

indexOf(char ch): int Returns the index within this string of the word.indexOf(‘p’);
first occurrence of the specified character. If
the character does not occur in the word, the
value -1 is returned.

indexOf(char ch, int fromIndex): Returns the index within this string of the word.indexOf(‘e’, 2);
int first occurrence of the specified character,
starting the search at the specified index. If
the character does not occur in the word, the
value -1 is returned.

indexOf(String str): int Returns the index within this string of the word.indexOf(“com”);
first occurrence of the specified substring. If
the String does not occur in the word, the
value -1 is returned.

indexOf(String str, int fromIndex): Returns the index within this string of the word.indexOf(“com”, 2);
int first occurrence of the specified substring,
starting at the specified index. If the String
does not occur in the word, the value -1 is
returned.

lastIndexOf(int ch): int Returns the index within this string of the word.lastIndexOf(‘x’);
last occurrence of the specified character. If
the letter does not occur, the value -1 is
returned.

lastIndexOf(int ch, int fromIndex): Returns the index within this string of the word.lastIndexOf(‘x’);
int last occurrence of the specified character,
searching backward starting at the specified
index. If the letter does not occur, the value
-1 is returned.

length(): int Returns an integer corresponding to the word.length();


number of characters in the string.

replace(char oldChar, char Returns a new string resulting from replacing word.replace(‘e’, ‘o’);
newChar): String all occurrences of oldChar in this string with
newChar.

split(String regex): String[] Splits a string around matches of the given word.split(“,”);
regular expression

substring(int start): String Returns a substring of the string, which word.substring(3);


starts at the start position and extends to
the end of the string.

substring(int start, int end): String Returns a substring of the string, which word.substring(0, 2);
starts at the start position and ends one
character before the end position

The String Class Page 2 of 6


toLowerCase(): String Converts all the characters of the string to word.toLowerCase();
lower case.

toUpperCase(): String Converts all the characters of the string to word.toUpperCase();


uppercase.

trim(): String Removes white space from both ends of the word.trim();
string.

COMPARING STRINGS
Comparing string values in Java is different than comparing the values that are stored in primitive Java
data types. Relational operators, including == and >, were used to compare primitive types. The
following are just some of the methods that can be used to compare data stored in one string variable to
data stored in another string:

METHOD DESCRIPTION EXAMPLE

compareTo(String str): int Compares two strings and returns if (guess.compareTo(password) == 0)


the value 0 when the strings are {
the same, otherwise returns a
value less than 0. Great to …
compare words alphabetically. }

compareToIgnoreCase Similar to compareTo() except it if (guess.compareToIgnoreCase(password) == 0)


(String str): int ignores the case considerations. {

}

contains(CharSequence cs): Returns true if the string contains if (guess.contains(“abc”))


boolean the specified sequence of char {
values, otherwise returns false.

}

endsWith(String str): boolean Tests if a string value ends with if (guess.endsWith(“ing”))


the specified suffix. {

}

equals(String str): boolean Compares a string value to if (guess.equals(password))


another string value. Returns {
true if the two strings are equal,
otherwise returns false. …
}

equalsIgnoreCase(String str): Compares a string value to if (guess.equalsIgnoreCase(password))


boolean another string value ignoring case {
considerations.

}

startsWith(String str): boolean Tests if a string begins with the if (guess.startsWith(“pre”))


specified prefix. {
….
}

The String Class Page 3 of 6


You can find the rest of the String class methods by referring to the Java API documentation.

COUNTING STRING INDEX


When we want to count character by character in a string, we need to note that the index value of a
string starts at zero (0). Therefore, it is important to make sure the loop iteration that steps through the
string starts at zero.

You can think of this indexing like a street with different mailboxes. Each character in the string
represents a different mailbox.

Therefore calling on #2, would produce is the letter N. Even though there are six (6) letters in the above
example, we can only call on the numbers from 0 – 5. If we try to call number six, we will get an
IndexOutOfBounds error, since index 6 does not exist in that string.

INDEXOUTOFBOUNDS ERROR
When we try to access a section in the string whose index does not exist, we get an error. The error is
called IndexOutOfBounds.

Since indexing starts at zero, this can occur if we also try to access the -1 index.

For example, the following lines will throw an error:

String word = “Java”;

char letter = word.charAt(4);

Even though there are four (4) letters in the string, the index ranges only from 0 – 3. Therefore as we try
to access the fourth (4th) index in a word, which does not exist, Java gets confused and throws an error.

The String Class Page 4 of 6


charAt() SAMPLE PROGRAM
The following program will demonstrate how to step through each character in a string the user enters,
and print each character on a new line.

import java.util.Scanner;

public class LetterWalkthrough{


public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);

String name;

System.out.print(“Enter in your name: ”);


name = scan.nextLine();

System.out.println();

for (int i = 0; i <name.length(); i++)


{
System.out.println(name.charAt(i));
}
}
}

The output looks like:

The String Class Page 5 of 6


substring() SAMPLE PROGRAM
The following program will demonstrate how to take the first half and last half of a name the user enters
and print each half on a new line.

import java.util.Scanner;

public class FirstProgram {

public static void main(String[] args)


{
Scanner scan = new Scanner (System.in);

String name, half1, half2;

System.out.print("Enter in your name: ");


name = scan.nextLine();

System.out.println();

half1 = name.substring(0, name.length() / 2);


half2 = name.substring(name.length() /2);

System.out.println("half1);
System.out.println("half2);
}
}

The output looks like:

SUCCESS CRITERIA:

• I can successfully identify the string method(s) needed for a given situation.
• I can successfully recall previous knowledge of loops and if statements and
integrate it into the new lesson involving strings.
• I can successfully extract the starting index and ending index characters of a
string for any length.
• I can successfully count indexes in a string.

The String Class Page 6 of 6

You might also like