Please enable JavaScript to use CodeHS

Chapter 2

Using Objects

2.7 String Methods

In this section, you will examine the different methods that can be run on String objects to create new, transformed String objects. You will also take a look at how Java uses libraries and documentation to help programmers implement more complex programs.

APIs, Libraries, and Documentation

Like physical town libraries, Java libraries and APIs (Application Programming Interface) are collections of written works made by other authors. An API is typically used to interface two systems and make using them easier. For example, if you wanted to program a robot in Java, you may use a set of commands from an API to control the motors. In contrast, libraries tend to be extensions of the main programming language that can help simplify your code since it takes common tasks and allows you to implement them without having to write out your own code.

Libraries can be broken down into a series of packages. Each package is then subdivided into specific classes with specific methods that can be run for that class. See the diagram below.

To help you do this, Java provides documentation. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. This section will focus on the Java String documentation, but you can find all the documentation for Java here: https://docs.oracle.com/javase/8/docs/api/

As a note, String objects are found in the java.lang package and are available by default in your programs.

Concatenating Strings with Reference Data Types

Just like you can concatenate primitive data types with strings, you can also concatenate reference data types with strings. In doing so, the reference data type’s toString() method gets called and concatenated to the existing String. The toString() method provides the string representation of the given object and is called anytime the object is referenced where it needs to be shown as a string, for example in a print statement.

Let’s look at an example of the Nickname class.

public class Nickname
{
  private String firstName;
  private String lastName;
  private String nickname;
  public Nickname(String realFirstName, String realLastName, String moniker)
  {
    firstName = realFirstName;
    lastName = realLastName;
    nickname = moniker;
  }
  public String toString()
  {
    return firstName + " (" + nickname + ") " + lastName;
  }
}
Plain text

Any Nickname object that is created has three different instance variables, so how does Java know what to use when you want to print out the name? It uses the toString() method. For example, if you create an object like this:

Nickname karel = new Nickname("Karel", "Dog", "the Dog");
Plain text

Then print the object using the following statement:

System.out.println(karel);
Plain text

You will get the following out:

Karel (the Dog) Dog
Plain text

Notice in the example above that you don’t specifically call the toString() method. The method is called implicitly when you use the object in a situation where a string is needed.

If you want to concatenate the output with another string, you can.

System.out.println(karel + " went to a movie.");
Plain text

Results:

Karel (the Dog) Dog went to a movie.
Plain text

See this example in action below.

Object Concatenation

String Index Values

You will remember that strings are a sequence of characters. Let’s look at this example String below:

String str = "Hello World"
Plain text

Here is a way to think about this String as a sequence of individual characters:

0 1 2 3 4 5 6 7 8 9 10
H e l l o W o r l d

Each character in this string has a position from 0 to 10. For example, the first character, 'H', is at position 0. The second character, 'e', is at position 1. The last character, 'd', is at position 10. Note that the space between the two words, ' ', is also a character and is located at position 5.

A character’s particular position in a string is formally known as its index. A String object has index values from 0 to the length of the string - 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.

Other Useful String Methods

Many useful String methods make use of the string’s index value. While there are many different String methods, there are several that are widely used within the AP Java programming course.

Method Use
String str2 = new String(str) Constructs a new String object that represents the same sequence of characters as str
name.length() Returns the number of characters in a String object
name.substring(2, 6) Returns the substring beginning at index 2 and ending at index 5.
name.substring(index, index + 1) Returns the string identical to the single element substring at position index
name.indexOf("d") Returns the index of the first occurrence of d; returns -1 if not found.
name.equals("Karel") Returns true if name is equal to Karel; returns false otherwise
name.compareTo("Karel") Returns a value < 0 if name is less than Karel; returns zero if name is equal to Karel; returns a value > 0 if name is greater than Karel.

Bigger Strings?

Chopping Strings

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What method must a class implement in order to concatenate an object of the class with a String object?

Exercise: toString for Plants

Complete the toString() method to the Plant Class. Remember that the format for a toString method is:

public String toString()
Plain text

The toString method should be formatted so that the following code

Plant swissCheesePlant = new Plant("Swiss Cheese Plant", "Green", "Monstera", "deliciosa");
System.out.println(swissCheesePlant);
Plain text

Prints out

Green Swiss Cheese Plant (Monstera deliciosa)
Plain text