APCS Java Subset

ap.java.lang
Class String

java.lang.Object
  |
  +--ap.java.lang.String
All Implemented Interfaces:
Comparable

public class String
extends java.lang.Object
implements Comparable

The class String represents a character string. Note that the primitive type char is not in the APCS Java subset, so individual characters of a String object aren't used in the APCS Java subset.

A String object is immutable, once created it cannot change. However, it is possible to re-assign a new String to an existing String variable/reference.

    String str = new String("hello");
    String w = new String("world");
    str = str + " " + w;            // now str represents "hello world"
 

In the code above, the String variable str references two objects: first an object representing the string "hello" and then an object representing the string "hello world" formed by concatenating three String objects. Note that the String object "hello" still exists, though it may eventually be garbage-collected since there is no reference to it.

There are six String methods specified as part of the APCS Java subset, these are described below. Although there are no constructors specified, this is an oversight and two constuctors will be part of the APCS subset as shown below.

In addition to these methods, the APCS Java subset specifies that String concatenation using + is part of the subset (see the example above) and that students are expected to know that concatenation invokes the toString method of an object.

For example, to construct and print String objects representing "1", "2", ... "9", the code below will work

   for(int k=1; k <= 9; k++) {
       String s = ""+9;
       System.out.println(s);
   }
 

Several methods that are not part of the APCS Java subset may be useful in programming. Some of these are shown below, see the Java java.lang.String API or a book for more details.

Useful String methods not in the APCS subset

The code below prints seven lines of output, "yes 1", "yes 2", ... "yes 7" since the expressions checked in each of the if statements are true.
  public static void main(String[] args)
  {
      String x = "HeLLo";
      String y = "hello";

      if (x.equalsIgnoreCase(y)) {     // case insensitive comparison
          System.out.println("yes 1");
      }
      
      x = x.toUpperCase();             // convert to upper case
      if ("HELLO".equals(x)) {          
          System.out.println("yes 2");
      }

      if (x.startsWith("HE")) {        // begins with substring
          System.out.println("yes 3");
      }

      if (x.charAt(0) == 'H') {        // access individual chars
          System.out.println("yes 4");
      }

      if (x.lastIndexOf("L") == 3) {   // last occurrrence of substring
          System.out.println("yes 5");
      }

      String xWithSpaces = "   " + x + "     ";

      if (! xWithSpaces.equals(x)) {  
          System.out.println("yes 6");
      }

      if (xWithSpaces.trim().equals(x)) { // trims leading/trailing whitespace
          System.out.println("yes 7");
      }
      
  }
  


Constructor Summary
String()
          Constructs a new string of no characters, that is whose length() method returns 0.
String(String s)
          Construct a new string that has the same character sequence as s.
 
Method Summary
 int compareTo(Object other)
          Compares two strings lexicographically.
 boolean equals(Object other)
          Returns true if and only if this String represents the same character sequence as the argument string.
 int indexOf(String s)
          Returns the index within this String of the first occurrence of s.
 int length()
          Returns the number of (Unicode) characters in this string.
 String substring(int firstIndex)
          Returns a new String that is a substring of this String.
 String substring(int firstIndex, int lastIndex)
          Returns a new String consisting of the characters with indexes in the range [from..to) from this String object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

String

public String()
Constructs a new string of no characters, that is whose length() method returns 0. This is the same as writing new String("").


String

public String(String s)
Construct a new string that has the same character sequence as s.

Parameters:
s - is the String whose character sequence is copied.
Method Detail

compareTo

public int compareTo(Object other)
Compares two strings lexicographically. Returns a negative number if this String is less than the String represented by the argument; returns a positive number if this String is greater than the argument; returns 0 if the two String objects are equal.

The lexicographic comparison is based on the character sequence represented by the strings. If there is a character that differs at the same valid index for both strings, then the character at the smallest such index determines the value returned. For example, "compute".compareTo("comb") returns a postive value since as characters 'p' > 'b'. If all valid characters are equal in both strings, then the length of the strings determines the value returned. For example "numb".compareTo("number") returns a negative value.

Specified by:
compareTo in interface Comparable
Parameters:
other - is the String to which this String is compared.
Returns:
0 if the strings are equal, a negative value if this string is less than the argument string, a positive value if this string is greater than the argument string.

equals

public boolean equals(Object other)
Returns true if and only if this String represents the same character sequence as the argument string.

Parameters:
other - is the String to which this String is compared.
Returns:
true if the strings are equal, otherwise return false

length

public int length()
Returns the number of (Unicode) characters in this string.

Returns:
the number of characters in this string

substring

public String substring(int firstIndex,
                        int lastIndex)
Returns a new String consisting of the characters with indexes in the range [from..to) from this String object.

The length of the new String is to-from since the valid indexes start at firstIndex and go up to lastIndex-1.

Examples:

     "programs".substring(3,7) returns "gram"
     "once".substring(3,4) returns "e"
 

Parameters:
firstIndex - is the first index, inclusive, of the returned substring
lastIndex - is the last index, exclusive, of the returned substring
Returns:
a substring as specified
Throws:
java.lang.IndexOutOfBoundsException - if firstIndex is negative or lastIndex is greater than the length of this String or firstIndex > lastIndex

substring

public String substring(int firstIndex)
Returns a new String that is a substring of this String. The call s.substring(k) return the same String that would be returned by s.substring(k,s.length()).

Parameters:
firstIndex - is the beginning index, inclusive.
Returns:
a substring as specified.
Throws:
java.lang.IndexOutOfBoundsException - if firstIndex is negative or larger than the length of this String

indexOf

public int indexOf(String s)
Returns the index within this String of the first occurrence of s. If s does not occur then -1 is returned.

For example:

    "splinter".indexOf("lint") returns 2
    "splinter".indexOf("line") return -1
 

Parameters:
s - is the substring searched for withing this String
Returns:
the index of the first occurrence of the String argument, or -1 if there no occurrence of the argument.

unofficial documentation for the APCS Java Subset