Skip to main content
Logo image

Section 1.15 Strings

Strings in Java are objects of the String class. Strings represent sequences of characters and are used to store text like names, addresses, or messages. The String class is part of the java.lang package which is available by default in all Java programs.

Note 1.15.1.

Class names in Java, like String, begin with a capital letter. All primitive types: int, double, and boolean, begin with a lowercase letter. This is one easy way to tell the difference between primitive types and class types.

Subsection 1.15.1 String References

Activity 1.15.1.

Run the following code. What does it print?
The code above declares an object variable named greeting and sets the value of greeting to the Java keyword null to show that it doesn’t refer to any object yet. So System.out.println(greeting); will print null.
Object variables refer to objects in memory. A reference is a way to find the actual object, like adding a contact to your phone lets you reach someone without knowing exactly where they are. The value of greeting is null since the string object has not been created yet.
Figure 1.15.2. Initial value for an object reference
In Java there are two ways to create an object of the String class. You can use the new keyword followed by a space and then the class constructor and then in parentheses you can include values used to initialize the fields of the object. This is the standard way to create a new object of a class in Java.
String greeting = new String("Hello");
In Java you can also use just a string literal, which is a set of characters enclosed in double quotes ("), to create a String object.
String greeting = "Hello";
In both cases an object of the String class will be created in memory and the value of the variable greeting will be set to an object reference, a way to find that object.

Activity 1.15.2.

The code below creates two greeting strings: one using a string literal and the other using new and the String constructor. Change the code to add 2 new strings called firstName and lastName, one using a string literal and the other using new, and print them out with the greetings.

Activity 1.15.3.

Now that greeting refers to an actual object we can ask the object what class created it. Try the following. What does it print?
The code above will first print class java.lang.String since greeting was created by the String class. The full name for the String class is java.lang.String. The java.lang part is the package name. Every class in the Java language is in a package and the standard classes like String are in the java.lang package. Every object in Java knows the class that created it. Also, every class knows its parent class. Yes, a class can have a parent class, just as people have parents. But, in Java a class can only have one parent. A class can inherit object fields and methods from a parent class, just like you might inherit musical ability from a parent. The last print statement will print class java.lang.Object because the parent class (superclass) of the String class is the Object class. All classes in Java inherit from the Object class at some point in their ancestry.
Figure 1.15.3. Object variable of type String with a reference to a String object which has a reference to the String class which has a reference to the Object class.

Subsection 1.15.2 String Operators - Concatenation

Strings can be added to each other to create a new string using the + or += operator . This is also called concatenation. You can also add any other kind of value to a String with + or += and the other value will be converted to a String automatically.
A String object is immutable, meaning once a String object is created, its attributes cannot be changed. So when we add two Strings (or a String and another value converted to a String) we get a new String without making any change to the values being added together just like when we add the ints 1 + 2 the original 1 and 2 aren’t changed. When we use += we are making a new String by adding something to the current value of a variable and then assigning that new value back into the variable, again just like with numbers.

Activity 1.15.4.

Try the following code. Add another variable for a lastname that is “Hernandez”. Use += or + to add the lastname variable after name to the result. Use += or + to add 2 more exclamation points (!) to the end of the happy birthday greeting in result.

Note 1.15.4.

Note that spaces are not added between strings automatically. If you want a space between two strings then add one using + ” ” +. If you forget to add spaces, you will get smushed output like “HiJose” instead of “Hi Jose”. And remember that variables are never put inside the quotes (“”) since this would print the variable name out letter by letter instead of its value.

Activity 1.15.5.

Given the following code segment, what is in the string referenced by s1?
String s1 = "xy";
String s2 = s1;
s1 = s1 + s2 + "z";
  • xyz
  • s1 will equal "xy" plus another "xy" then z at the end.
  • xyxyz
  • s1 contains the original value, plus itself, plus "z"
  • xy xy z
  • No spaces are added during concatenation.
  • xy z
  • No spaces are added during concatenation, and an additional "xy" should be included at the beginning.
  • z
  • s1 was set to "xy" initially, so the final answer will be "xyxyz"
You can even add other items to a String using the + operator. Primitive values like int and boolean will be converted to a String automatically when concatenated with a String. Any other objects concatenated with a String will be converted to String using their toString method. All objects inherit a toString method from the Object class that returns a String representation of the object and many classes override it to produce a useful human-readable value. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass (overriding toString is no longer covered on the AP CSA exam).

Activity 1.15.6.

What do you think the following will print? Guess before you hit run. If you want the addition to take place before the numbers are turned into a string what should you do? Try to modify the code so that it adds 4 + 3 before appending the value to the string. Hint: you used this to do addition before multiplication in arithmetic expressions.

Note 1.15.5.

If you are appending a number to a string it will be converted to a string first before being appended.
Since the same operators are processed from left to right this will print 1243. First 4 will be turned into a string and appended to 12 and then 3 will be turned into a string and appended to 124. If you want to do addition instead, try using parentheses!

Subsection 1.15.3 String Index and Length

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.
Figure 1.15.6. A string with the position (index) shown above each character

Note 1.15.7.

The first character in a string is at index 0 and the last characters is at length -1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.

Subsection 1.15.4 String Methods

The String class includes many methods to process strings. For the AP CSA exam, you only need to know how to use the following String methods. Their descriptions are included in the AP CSA Java Quick Reference Sheet
 1 
https://apstudents.collegeboard.org/ap/pdf/ap-computer-science-a-java-quick-reference_0.pdf
that you get during the exam so you don’t have to memorize these.
  • int length() method returns the number of characters in the string, including spaces and special characters like punctuation.
  • String substring(int from, int to) method returns a new string with the characters in the current string starting with the character at the from index and ending at the character before the to index (if the to index is specified, and if not specified it will contain the rest of the string).
  • int indexOf(String str) method searches for the string str in the current string and returns the index of the beginning of str in the current string or -1 if it isn’t found.
  • int compareTo(String other) returns a negative value if the current string is less than the other string alphabetically, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the other string alphabetically.
  • boolean equals(String other) returns true when the characters in the current string are the same as the ones in the other string. This method is inherited from the Object class, but is overridden which means that the String class has its own version of that method.

Subsection 1.15.5 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) searches for the substring in str and returns the index of where it finds substring in str or -1 if it is not there.

Activity 1.15.7.

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 1.15.8.

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(i, i + 1).

Activity 1.15.8.

The following code breaks the preconditions of the substring method and throws an IndexOutOfBoundsException. Can you fix the code by changing the arguments for the substring method to print out the substring “o”?

Activity 1.15.9.

What is the value of pos after the following code executes?
String s1 = "abccba";
int pos = s1.indexOf("b");
  • 2
  • The first character is at index 0 in a string.
  • 1
  • The method indexOf returns the first position of the passed str in the current string starting from the left (from 0).
  • 4
  • Does indexOf start from the left or right?
  • -1
  • Does the string contain a b?

Activity 1.15.10.

What is the value of len after the following code executes?
String s1 = "baby";
int len = s1.length();
  • 2
  • Length returns the number of characters in the string, not the number of characters in the name of the string.
  • 3
  • The position of the last character is 3, but the length is 4.
  • 4
  • Length returns the number of characters in the string.
  • -1
  • Length is never negative.

Activity 1.15.11.

What is the value of s2 after the following code executes?
String s1 = "baby";
String s2 = s1.substring(0,3);
  • baby
  • This would be true if substring returned all the characters from the first index to the last inclusive, but it does not include the character at the last index.
  • b
  • This would be true if it was s1.substring(0,1)
  • ba
  • This would be true if it was s1.substring(0,2)
  • bab
  • Substring returns all the characters from the starting index to the last index -1.

Activity 1.15.12.

What is the value of s2 after the following code executes?
String s1 = "baby";
String s2 = s1.substring(2);
  • by
  • The method substring(index) will return all characters starting the index to the end of the string.
  • aby
  • This would be true if it was substring(1);
  • a
  • This would be true if it was substring(1,2);
  • b
  • This would be true if it was substring(2,3);
  • ba
  • This would be ture if it was substring(0,2);

Subsection 1.15.6 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.)
Figure 1.15.9. 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, which are not on the AP exam.
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.

Activity 1.15.13.

Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number?
There are lots of other methods in the String class. You can look through the Java documentation for the String class
 2 
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
online. You don’t have to know all of these for the exam, but you can use them if you want to on the exam.

Activity 1.15.14.

Activity 1.15.15.

Activity 1.15.16.

What is the value of answer after the following code executes?
String s1 = "Hi";
String s2 = "Bye";
int answer = s1.compareTo(s2);
  • positive (> 0)
  • H is after B in the alphabet so s1 is greater than s2.
  • 0
  • The method compareTo will only return 0 if the strings have the same characters in the same order.
  • negative (< 0)
  • This would be true if it was s2.compareTo(s1)

Subsection 1.15.7 Common Mistakes with Strings

The following code shows some common mistakes with strings.

Activity 1.15.17.

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.

Subsection 1.15.8 Coding Challenge : Pig Latin

Can you speak Pig Latin? In Pig Latin, you take the first letter and put it at the end of the word and add the letters “ay” to the end. For example, “pig” becomes “igpay”.
Create a program that takes a word and transforms it to Pig Latin using String methods. You may need the word’s length, a substring that does not include the first letter, and a substring that is just the first letter (you can get the ith letter of a string using substring(i,i+1) so for example the letter at index 3 would be substring(3,4)).

Project 1.15.18.

Write code in the pigLatin method below to use the substring method to transform a word given as its argument into Pig Latin where the first letter is put at the end and “ay” is added. The word pig is igpay in Pig Latin. Change the input below to try it on other words.

Subsection 1.15.9 Summary

  • (AP 1.15.A.1) A String object represents a sequence of characters and can be created by using a string literal.
  • (AP 1.15.A.2) The String class is part of the java.lang package. Classes in the java.lang package are available by default.
  • String objects can be created by using string literals (String s = “hi”;) or by calling the String class constructor (String t = new String(“bye”);).
  • (AP 1.15.A.3) A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
  • (AP 1.15.A.4) Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object.
  • (AP 1.15.A.4) A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
  • (AP 1.15.A.5) A String object can be concatenated with any object, which implicitly calls the object’s toString method (a behavior which is guaranteed to exist by the inheritance relationship every class has with the Object class). An object’s toString method returns a string value representing the object. Subclasses of Object often override the toString method with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass. Overriding the toString method of a class is outside the scope of the AP CSA exam.
  • 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.
  • (AP 1.15.B.1) A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.
  • (AP 1.15.B.2) The following String methods and constructors, including what they do and when they are used, are part of the AP CSA Java Quick Reference Sheet
     3 
    https://apstudents.collegeboard.org/ap/pdf/ap-computer-science-a-java-quick-reference_0.pdf
    that you can use during the exam:
    • 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) : searches for str in the current string and 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. Using the equals method to compare one String object with an object of a type other than String is outside the scope of the AP CSA exam.
    • 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. Strings are ordered based upon the alphabet.
  • str.substring(index, index + 1) returns a single character at index in string str.

Subsection 1.15.10 AP Practice

Activity 1.15.19.

What is the value of s2 after the following code executes?
String s1 = new String("hi there");
int pos = s1.indexOf("e");
String s2 = s1.substring(0,pos);
  • hi th
  • The substring method returns the string starting at the first index and not including the last index. The method indexOf returns the index of the first place the string occurs.
  • hi the
  • This would be correct if substring returned all characters between the first index and last index, but does it?
  • hi ther
  • This would be correct if indexOf returned the last position the string str was found in the current string, does it?
  • hi there
  • This would be correct if indexOf returned the last position the string str was found in the current string and if substring included all characters between the start and end index. Check both of these.

Activity 1.15.20.

What is the value of s1 after the following code executes?
String s1 = "Hi";
String s2 = s1.substring(0,1);
String s3 = s2.toLowerCase();
  • Hi
  • Strings are immutable, meaning they don’t change. Any method that changes a string returns a new string. So s1 never changes.
  • hi
  • This would be true if the question was what is the value of s2 and it was substring(0,2) not (0,1)
  • H
  • This would be true if the question was what is the value of s2, not s1.
  • h
  • This would be true if the question was what is the value of s3, not s1.

Note 1.15.10.

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. The original string is not changed.

Subsection 1.15.11 String Methods Game

Try the game below written by AP CSA teacher Chandan Sarkar. Click on Strings and then on the letters that would be the result of the string method calls. We encourage you to work in pairs and see how high a score you can get.

Subsection 1.15.12 Review/Practice for Unit 1 Part 3 on Using Objects

This lesson ends the section on Unit 1 part 3 on Using Objects. You can now do the following review and practice lessons at the end of the unit and College Board Progress Check for Unit 1 Part 3 in the AP Classroom. Please do the practice test on objects and the FRQ practice below before you do the AP Classroom Progress Check for part 3.
You have attempted of activities on this page.