5 Steps to a 5 AP Computer Science A 2017 (2016)


Review the Knowledge You Need to Score High


The String Class


Summary: When people think of the word data , they usually think “numbers.” However, non-numerical data can be stored in a computer too. In this concept, you will learn how letters, words, and even sentences are stored in variables. String objects can store alphanumerical data, and the methods from the String class can be used to manipulate this data.

Key Ideas

   Strings are used to store letters, words, and other special characters.

   To concatenate strings means to join them together.

   The String class has many methods that are useful for manipulating String objects.

The String Variable

How does Twitter know when a tweet has more than 140 characters? How does the computer know if your username and password are correct? How are Facebook posts stored? What we need is a way to store letters, characters, words, or even sentences if we want to make programs that are useful to people. The String data type helps solve these problems.

When we wanted to store numbers so that we can retrieve them later, we created either an int or double variable. Now that we want to store letters or words, we need to create String variables . A String can be a single character or group of characters like a word or a sentence. String literals are characters surrounded by double quotation marks.

General Way to Make a String Variable and Assign It a Value


Make some String variables and assign them values:

The String Object

String variables are actually objects. The String class is unique because String objects can be created by simply declaring a String variable like we did above or by using the constructor from the String class. The reference variable knows the address of the String object. The object is assigned a value of whatever characters make up the String literal.

General Way to Make a String Object Using the Constructor from the String Class

Example 1

Make a String object and assign it a value:

Example 2

Create a String object, but don’t give it an initial value (use the empty constructor from the String class). The String object contains an empty string , which means that the value exists (it is not null); however, there are no characters in the String literal and it has a length of 0 characters.

Example 3

Create a String reference variable but don’t create a String object for it. The String reference variable is assigned a value of null because there isn’t an address of a String object for it to hold.

null String Versus Empty String

null string is a string that has no value and no length. It does not hold an address of a String object.

An empty string is a string that has a value of "" and its length is zero. There is no space inside of the double quotation marks, because the string is empty.

It may seem like they are the same thing, but they are not. The difference is subtle. The empty string has a value and the null string does not. Furthermore, you can perform a method on an empty string, but you cannot perform a method on a null string .

Any attempt to execute a method on a null string will result in a run-time error called a NullPointerException .

A Visual Representation of a String Object

This is a visual representation of what a string looks like in memory. The numbers below the characters are called the indices (plural of index ) of the string. Each index represents the location of where each of the characters lives within the string. Notice that the first index is zero. An example of how we read this is: the character at index 4 of myFavoriteFoodGroup is the character “c”. Also, spaces count as characters. You can see that the character at index 3 is the space character.

String Concatenation

Now that you know how to create a string and give it a value, let’s make lots of them and string them together (Ha!). The process of joining strings together is called concatenation . The + and += signs are used to concatenate strings.

Example 1

Concatenate two strings using +

Example 2

Concatenate two strings using +=

Example 3

Concatenate a number and a string using +

Example 4

Incorrectly concatenate a string and the sum of two numbers using +. Notice that the sum is not computed.

Example 5

Correctly concatenate a string and the sum of two numbers using +

Example 6

Concatenate the sum of two numbers and a string in a different order. Notice that when the numbers come first in the concatenation, the sum is computed.


Strings can be joined together to form a new string using concatenation. The + sign or the += operation may be used to join strings.

You can even join an int or a double along with a string. These numbers will be rendered useless for any mathematical purpose because they are turned into strings.

The Correct Way to Compare Two String Objects

Everyone reading this book has had to log into a computer at some time. How does the computer know if the user typed the username and password correctly? The answer is that the software uses an operation to compare the input with the information in a database.

In Java, we can determine if two strings are equal to each other. This means that the two strings have exactly the same characters in the same order.

The Correct Way to Compare Two String Objects

Use the equals method or the compareTo method to determine if two String variables contain the exact same character sequence.

Important String Methods

The equals Method

The equals method returns a boolean answer of true if the two strings are identical and it returns an answer of false if the two strings differ in any way. The equals method is case-sensitive , so, for example, the uppercase “A” is different than the lowercase “a”. The ! operator can be used in combination with the equals method to compare if two strings are not equal.

Example 1

Compare if two strings are equal:

Example 2

Compare if two strings are not equal:

Never Use == to Compare Two String Objects

We used the double equals (== ) to compare if two numbers were the same. However, == does not correctly tell you if two strings are the same. What’s worse is that comparing two strings using == does not throw an error, it simply compares whether or not the two String references point to the same object. Even worse is that sometimes it appears to work correctly. Just don’t do it!

The compareTo Method

The second way to compare two strings is to use the compareTo method. Instead of returning an answer that is a boolean like the equals method did, the compareTo method returns an integer. The result of the compareTo method is a positive number, a negative number, or zero. This integer describes how the two strings are ordered lexicographically ; a case-sensitive ordering of words similar to a dictionary but using the UNICODE codes of each character.

The compareTo Method

The compareTo method returns an integer that describes how the two strings compare.

  • The answer is zero if the two strings are exactly the same.
  • The answer is negative if firstString comes before secondString (lexicographically).
  • The answer is positive if firstString comes after secondString (lexicographically).

Example 1

The answer is zero if the two strings are exactly the same:

Example 2

The answer is negative when the first string comes before the second string (lexicographically):

Example 3

The answer is positive when the first string comes after the second string (lexicographically):

Example 4

Uppercase letters come before their lowercase counterparts. "Hello" comes before "hello" when comparing them using lexicographical order:

Fun Fact : Unicode is a worldwide computing standard that assigns a unique number to nearly every possible character (including symbols) for every language. There are more than 120,000 characters listed in the latest version of Unicode. For example, the uppercase letter "A" is 41 (hexadecimal), the lowercase letter "a" is 61 (hexadecimal), and "ñ" is F1 (hexadecimal) .

The length Method

The length method returns the number of characters in the specified string (including spaces).

Example 1

Find the length of a string:

Example 2

Find the length of a string that is empty, but not null (it has "" as its value):

Example 3

Attempt to find the length of a string that is null:

The NullPointerException

Attempting to use a method on a string that has not been initialized will result in a runtime error called a nullPointerException. The compiler is basically telling you that there isn’t an object to work with, so how can it possibly perform any actions with it?

The indexOf Method

To find if a string contains a specific character or group of characters, use the indexOf method. It searches the string and if it locates what you are looking for, it returns the index of its location. Remember that the first index of a string is zero. If the indexOf method doesn’t find the string that you are looking for, it returns -1.

Example 1

Find the index of a specific character in a string:

Example 2

Find the index of a character in a string when it appears more than once:

Example 3

Attempt to find the index when the character is not in the string:

Example 4

Find the index of a string inside a string:

The substring Method

The substring method is used to extract a specific character or group of characters from a string. All you have to do is tell the substring method where to start extracting and where to stop.

The substring method is overloaded . This means that there is more than one version of the method.

Example 1

Extract every character starting at a specified index from a string:

Example 2

Extract one character from a string:

Example 3

Extract two characters from a string:

Example 4

Extract the word “force” from a string:

Example 5

Use numbers that don’t make any sense:

The StringIndexOutOfBoundsException

If you use an index that doesn’t make any sense, you will get a run-time error called a StringIndexOutOfBoundsException . Using an index that is greater than or equal to the length of the string or an index that is negative will produce this error.

Example 6

Extract the word "the" from the following string by finding and using the first and second spaces in the string:

Helpful Hint for the substring Method

To find out how many characters to extract, subtract the first number from the second number.

Since 13 − 5 = 8, the result contains a string that is a total of eight characters.

Note: When the start index and end index are the same number, the substring method does not return a character of the string; it returns the empty string "".

A String Is Immutable

String variables are actually references to String objects, but they don’t operate the same way as normal object reference variables.

Every time you make a change to a String variable, Java actually tosses out the old object and creates a new one. You are never actually making changes to the original String object and resaving the same object with the changes. Java makes the changes to the object and then creates a brand-new String object and that is what you end up referencing.


Demonstrate how a String variable is immutable through concatenation. Even though it seems like you are modifying the String variable, you are not. A completely brand-new String object is created and the variable is now referencing it:

Escape Sequences

How would you put a double quotation mark inside of a string? An error occurs if you try because the double quotes are used to define the start and end of a String literal. The solution is to use an escape sequence .

Escape sequences are special codes that are sent to the computer that say, “Hey, watch out, something different is coming.” They use a backslash followed by a special character. Escape sequences are commonly used when concatenating strings to create a single string. Here are the most common escape sequences.

 Rapid Review


  • The String class is used to store letters, numbers, or other symbols.
  • A String literal is a sequence of characters contained within double quotation marks.
  • You can create a String variable by declaring it and directly assigning it a value.
  • You can create a String variable using the keyword new along with the String constructor.
  • Strings are objects from the String class and can utilize methods from the String class.
  • Strings can be concatenated by using the + or += operators.
  • Only compare two String variables using the equals method or the compareTo method.
  • Strings should never be compared using the = = comparator.
  • Every character in a string is assigned an index. The first index is zero. The last index is one less than the length of the string.
  • Escape sequences are special codes that are embedded in String literals to perform such tasks as issuing a new line or a tab, or printing a double quote or a backslash.
  • A null string does not contain any value. It does not reference any object.
  • If a string is null, then no methods can be performed on it.
  • A NullPointerException is thrown if there is any attempt to perform a method on a null string.
  • An empty string is not the same as a null string.
  • An empty string has a value of "" and a length of zero.

String Methods

  • The equals(String other) method returns true if the two strings that are being compared contain exactly the same characters.
  • The compareTo(String other) method compares two strings lexicographically.
  • Lexicographical order is a way of ordering words based on their Unicode values.
  • The length() method returns the number of characters in the string.
  • The indexOf(String str) method finds and returns the index value of the first occurrence of str within the String object that called the method. The value of -1 is returned if str is not found.
  • The substring(int index) method returns a new String object that begins with the character at index and extends to the end of the string.
  • The substring(int beginIndex, int endIndex) method returns a new String object that begins at the beginIndex and extends to the character at endIndex – 1.
  • Strings are immutable. A new String object is created each time changes are made to the value of a string.
  • A StringIndexOutOfBoundsException error is thrown for any attempt to access an index that is not in the bounds of the String literal.

 Review Questions

Basic Level

   1 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A) HomeHello

(B) HelloHello

(C) WelcomeHello

(D) Welcome Hello

(E) Home Hello

   2 .    What is printed as a result of executing the following statement?

(A) 7878Hello7878

(B) 7815Hello7815

(C) 30Hello30

(D) 30Hello7815

(E) 7815Hello30

   3 .    Consider the following method.

What is returned by the call mixItUp("AP", "CS") ?

(A) "APAP"





   4 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A) p0

(B) r9

(C) r10

(D) ra9

(E) ra10

   5 .    Consider the following code segment.

Which of these could be the result of executing the code segment?

(A) 0 0

(B) -1 -1

(C) -1 1

(D) 1 -1

(E) 1 1

   6 .    Which of the following returns the last character of the string str ?

(A) str.substring(0);

(B) str.substring(0, str.length());

(C) str.substring(length(str));

(D) str.substring(str.length() - 1);

(E) str.substring(str.length());

Advanced Level

   7 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A) amxem

(B) amxema

(C) amxepma

(D) ampxepm

(E) The program will terminate with a StringIndexOutOfBoundsException

   8 .    Consider the following method.

What is the purpose of the method whatDoesItDo ?

(A) The method returns true if st has an even length, false if it has an odd length.

(B) The method returns true if st contains any character more than once.

(C) The method returns true if st is a palindrome (spelled the same backward and forward), false if it is not a palindrome.

(D) The method returns true if st begins and ends with the same letter.

(E) The method returns true if the second half of st contains the same sequence of letters as the first half, false if it does not.

   9 .    Consider the following method.

What is returned as a result of the call firstLetterIndex("on your side") ?

(A) -1

(B) 0

(C) 3

(D) 4

(E) 5

10 .    Which print statement will produce the following output?

(A) System.out.print("/\\what\ttime\n\"is it?\"//\\\\");

(B) System.out.print("//\\what\ttime\n\"is it?\"////\\\\");

(C) System.out.print("/\\what\time\n\"is it?\"//\\\\");

(D) System.out.print("/\\what\ttime\n"is it?"//\\\\");

(E) System.out.print("//\\what\time + \"is it?\"////\\\\");

 Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

   1 .    The answer is A.

  • When two strings are concatenated (added together), the second one is placed right after the first one (do not add a space).

   2 .    The answer is D.

  • This question requires that you understand the two uses of the + symbol.
  • First, execute what is in the parentheses. Now we have:
  • Now do the addition left to right. That’s easy until we hit the string:
  • When you add a number and a string in any order, Java turns the number into a string and then concatenates the string:
  • Now every operation we do will have a string and a number, so they all become string concatenations, not number additions.

   3 .    The answer is C.

  • To answer this problem, you need to understand that String objects are immutable (the only other immutable objects in our Java subset are Integer and Double, which we will learn about in Concept 4).
  • When the method begins, entry1 = "AP" and entry2 = "CS".
  • Then the assignment statement reassigns entry2 so that both variables now refer to the String object containing "AP".
  • When we execute the next statement, entry1 = entry1 + entry2, we would expect that to change for both variables, since they both reference the same object, but String objects don’t work that way. Whenever a string is modified, a new String object is created to hold the new value. So now, entry1 references "APAP" but entry2 still references "AP".
  • We put those together, and “APAPAP” is returned.

   4 .    The answer is B.

  • The indexOf method returns the index location of the parameter.
  • The letter "a" has index 9 in "presto chango" (remember to start counting at 0).
  • The substring will start at index 9 and stopbefore index 10, meaning it will return only the letter at index 9 in "abracadabra".
  • Once again, start counting at 0. Index 9 of "abracadabra" is "r".
  • Concatenate that with i which equals 9. Print "r9".

   5 .    The answer is C.

  • CompareTo takes the calling string and compares it to the parameter string. If the calling string comesbefore the parameter string, it returns a negative number. If it comes after the parameter string, it returns a positive number. If they are equal, it returns 0.
  • The first compareTo is "avocado".compareTo("banana") so it returns -1.
  • The second compareTo switches the order to "banana".compareTo("avocado") so it returns 1.
  • Note that although we often only care about whether the answer is positive or negative, the actual number returned has meaning. Because "a" and "b" are one letter apart, 1 (or -1) is returned. If the example had been "avocado" and "cucumber", 2 (or -2) would have been returned.

   6 .    The answer is D.

  • Let’s take the word "cat" as an example. It has a length of 3, but the indices of its characters are 0, 1, 2, so the last character is at length – 1.
  • We need to start our substring at str.length() – 1. We could say:

but since we want the string all the way to the end we can use the single parameter version of substring.

   7 .    The answer is B.

  • ex1.substring(1, ex1.indexOf("p"))starts at the character at index 1 (remember we start counting at 0) and ends before the index of the letter "p". ex1 now equals "xam".
  • Let’s take this one substring at a time. At the beginning of the statement, ex2 = "elpmaxe".
  • ex2.substring(3, ex1.length()) The length of ex1 is 3, so this substring starts at the character at index 3 and ends before the character at index 3. It stops before it has a chance to begin and returns the empty string. Adding that to the current value of ex2 does not change ex2 at all.
  • ex2.substring(3, ex2.length()) starts at the character at index 3 and goes to the end of the string, so that’s "maxe".
  • Add that to the current value of ex2 and we have "elpmaxemaxe".
  • We are going to take two substrings and assign them to ex3.
  • The first one is isn’t too bad. ex1 = “xam”, so ex1.substring(1) = "am". Remember that if substring only has 1 parameter, we start there and go to the end of the string.
  • The second substring has two parameters. Let’s start by figuring out what the parameters to the substring are equal to.
  • Remember ex2 = "elpmaxemaxe" so indexOf("x") is 5.
  • The second parameter is ex2.length() – 2. The length of ex2 = 11, subtract 2 and the second parameter = 9.
  • Now we can take the substring from 5 to 9, or from the first "x" to just before the second "x", which gives us "xema".
  • Add the two substrings together: "amxema"

   8 .    The answer is C.

  • This method takes a String parameter and loops through the first half of the letters in the string.
  • The first substring statement assigns the letter at index i to sub1. You may have to run through an example by hand to discover what the second substring does.
  • If our string is “quest”:
  • the first time through the loop, i = 0, so sub1 = "q" and sub2 = st.substring(5 – 0 – 1, 5 – 0) = "t".
  • the second time, i = 1, so sub1 = "u" and sub2 = st.substring(5 – 1 – 1, 5 – 1) = "s".
  • This loop is comparing the first letter to the last, the second to the second to last, and so on, which will tell us if the string is a palindrome.

   9 .    The answer is C.

  • Let’s figure this out step by step. The length of "on your side" is 12 (don’t forget to count spaces), sos1.indexOf(s2.substring(s2.length() - 2)) simplifies to s1.indexOf(s2.substring(10))
  • That gives us the last two letters of s2, so our statement becomess1.indexOf("de")
  • Can we find "de" in s1? Yes. It starts at index 3 and that is what is returned.

10 .    The answer is A.

  • Let’s take this piece by piece. A forward slash "/" does not require an escape sequence, but a backslash needs to be doubled since "\" is a special character. Our print sequence needs to start:/\\
  • The next interesting thing that happens is the tab before "time". The escape sequence for tab is"\t" . Our print sequence is now: /\\what\ttime (Don’t be confused by the double t. One belongs to "\t" and the other belongs to "time".)
  • Now we need to go to then next line. The newline escape sequence is"\n"
  • We also need escape sequences for the quote symbols, so now our print sequence is:/\\what\ttime\n\"is it\"
  • Add the last few slashes, remembering to double the "\" and we’ve got our final result./\\what\ttime\n\"is it?\"//\\\\