impera Open Impera

AP Computer Science A · Using objects and methods

The String and Math classes

1String basics

A String is an object holding a sequence of characters. Strings are immutable: once created, they cannot change; methods that seem to change a string return a new one.

String s = "computer";

Characters are numbered from index 0 to length() - 1. For "computer", c is at index 0 and r at index 7.

Concatenation with + joins strings: "AP " + "CSA" is "AP CSA". If one operand is a string, the other is converted: "Score: " + 9 is "Score: 9". Evaluation is left to right: 1 + 2 + "x" is "3x" but "x" + 1 + 2 is "x12".

Check yourself

What is "x" + 3 + 4?

  • "x7"

  • An error

  • "x34"

  • "7x"

Show the answer

"x34"

Left to right with a String.

2String methods

Key methods (on the AP Java Quick Reference):

  • length(): number of characters.
  • substring(a, b): characters from index a up to but not including b.
  • substring(a): from index a to the end.
  • indexOf(str): index of the first occurrence of str, or −1 if not found.
  • equals(other): true if the characters are the same.
  • compareTo(other): negative if this string comes first alphabetically, 0 if equal, positive if it comes after.
Worked example

String s = "computer";

  1. s.length() → 8.
  2. s.substring(3, 6) → "put".
  3. s.substring(5) → "ter".
  4. s.indexOf("t") → 5; s.indexOf("z") → −1.

String indices start at 0; substring(a, b) stops just before b

Using an index outside 0 to length() throws StringIndexOutOfBoundsException.

Check yourself

For s = "planet", s.substring(1, 4) is:

  • "an"

  • "plan"

  • "lane"

  • "lan"

Show the answer

"lan"

Indices 1, 2, 3.

3Comparing strings

  • Use s.equals(t) to compare contents.
  • s == t compares references (whether both variables point to the same object), which can be false even when the characters match.
  • Use compareTo for alphabetical order: "apple".compareTo("banana") is negative.
Check yourself

Which correctly tests whether two strings have the same characters?

  • a.compareTo(b) == 1

  • a = b

  • a == b

  • a.equals(b)

Show the answer

a.equals(b)

equals compares contents.

4The Math class

Math methods are static: call them on the class name.

  • Math.abs(x): absolute value.
  • Math.pow(base, exp): returns a double.
  • Math.sqrt(x): square root, a double.
  • Math.random(): a double in the range $[0.0, 1.0)$.

Random integers: to get a random int from low to high inclusive:

int r = (int) (Math.random() * (high - low + 1)) + low;
Worked example

a dice roll from 1 to 6: (int) (Math.random() * 6) + 1.

  1. Math.random() * 6 is in $[0, 6)$.
  2. Casting gives 0, 1, 2, 3, 4 or 5.
  3. Adding 1 gives 1 to 6.
Check yourself

Which expression gives a random int from 10 to 20 inclusive?

  • (int) (Math.random() * 10) + 10

  • (int) Math.random() * 11 + 10

  • (int) (Math.random() * 20) + 10

  • (int) (Math.random() * 11) + 10

Show the answer

(int) (Math.random() * 11) + 10

11 possible values starting at 10.

5Going deeper: string algorithms, bounds and random numbers

Strings are immutable. No method changes a String; each returns a new one. To keep the result, assign it: s = s.toUpperCase();.

Indexing: positions run from 0 to length() - 1.

The methods to know

  • length(): number of characters.
  • substring(from, to): characters from index from up to but not including to. Its length is to - from.
  • substring(from): from from to the end.
  • indexOf(str): index of the first occurrence, or −1 if absent.
  • equals(other): true if the characters match exactly.
  • compareTo(other): negative if this string comes first alphabetically, zero if equal, positive if it comes after.

For String s = "COMPUTER"; (length 8):

  • s.substring(3, 6) is "PUT".
  • s.substring(5) is "TER".
  • s.substring(8) is "" (allowed: the empty string).
  • s.substring(4, 9) throws a StringIndexOutOfBoundsException.
  • s.indexOf("UT") is 4; s.indexOf("x") is −1.

One character at a time: s.substring(i, i + 1) is the single character at index i, as a String.

Compare strings with equals, never ==. == asks whether two variables refer to the same object.

compareTo: "apple".compareTo("banana") is negative. Capital letters come before lower-case ones, so "Zebra".compareTo("apple") is negative too.

Worked example (count occurrences of a letter):

int count = 0;
for (int i = 0; i < word.length(); i++) {
    if (word.substring(i, i + 1).equals("s")) {
        count++;
    }
}

For "mississippi" the result is 4.

Worked example (reverse a string):

String result = "";
for (int i = word.length() - 1; i >= 0; i--) {
    result += word.substring(i, i + 1);
}
  1. Start at the last index, length() - 1.
  2. Continue while i >= 0.
  3. For "cat": result becomes "t", "ta", "tac".

Worked example (looking at pairs): to test neighboring characters, stop one early.

for (int i = 0; i < word.length() - 1; i++) {
    String pair = word.substring(i, i + 2);
    // examine pair
}

With i < word.length() the last pass would ask for a character past the end.

Worked example (split at a space): for String full = "Ada Lovelace";

  1. int sp = full.indexOf(" "); gives 3.
  2. full.substring(0, sp) is "Ada".
  3. full.substring(sp + 1) is "Lovelace".

The Math class: all methods are static; call them with the class name.

  • Math.abs(x): absolute value (int or double).
  • Math.pow(base, exp): returns a double: Math.pow(2, 3) is 8.0.
  • Math.sqrt(x): returns a double.
  • Math.random(): a double from 0.0 (inclusive) to 1.0 (exclusive).

Random integers in a range

int r = (int) (Math.random() * numberOfValues) + lowest;
  • 1 to 6 (a die): (int) (Math.random() * 6) + 1.
  • 0 to 9: (int) (Math.random() * 10).
  • 5 to 15 inclusive: there are 11 values: (int) (Math.random() * 11) + 5.
  • In general, for min to max inclusive: (int) (Math.random() * (max - min + 1)) + min.

The parentheses matter: (int) Math.random() * 6 casts first, giving 0 every time.

A random index: (int) (Math.random() * arr.length).

Common mistakes

  • Calling s.toUpperCase(); and expecting s to change.
  • Thinking the second argument of substring is included, or is a length.
  • Using == to compare strings.
  • Forgetting indexOf can return −1, then using that as an index.
  • Miscounting the number of values in a random range.
  • Storing Math.pow or Math.sqrt in an int without a cast.
Check yourself

Which expression gives a random integer from 10 to 20 inclusive?

  • (int) (Math.random() * 10) + 10

  • (int) (Math.random() * 11) + 10

  • (int) (Math.random() * 20) + 10

  • (int) Math.random() * 11 + 10

Show the answer

(int) (Math.random() * 11) + 10

There are 11 possible values, starting at 10.

6For top marks

  • Remember that substring(a, b) excludes index b and has length b − a.
  • Check for −1 when using indexOf.
  • Use a loop with substring(i, i + 1) to look at one character at a time.
  • Cast the whole product in random-number formulas: (int) (Math.random() * n).
Example

count the vowels in a string:

int count = 0;
for (int i = 0; i < s.length(); i++) {
    if ("aeiou".indexOf(s.substring(i, i + 1)) >= 0) count++;
}
Check yourself

For s = "java", what is s.substring(s.length() − 1)?

  • An exception

  • "java"

  • "a"

  • "v"

Show the answer

"a"

The last character.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera