Lesson 4: Strings, Math and the AP Java Quick Reference
The String class is the most used class in the course, and its methods repay careful study. A String is an immutable sequence of characters, indexed from zero: in "Hello", H is at index 0 and o is at index 4. The method length() gives the number of characters, charAt(i) gives the character at index i, substring(a, b) gives the characters from a up to but not including b, indexOf(s) gives the first position of s or −1 if it is absent, and equals compares contents. Immutability means these methods never change the String — substring returns a new String, and the original is untouched — which is a frequent source of exam questions.
String methods are easy to misuse in small ways that matter. substring(2, 5) on a five-character String gives the characters at indices 2, 3, and 4, and calling substring with an index outside the String throws a StringIndexOutOfBoundsException. Comparing Strings with == compares references, not contents, so equals is the correct test. Concatenation with + builds a new String, and adding a number to a String converts the number to text: "Score: " + 90 gives "Score: 90". When you trace String code, write the String out with its indices underneath — the diagram makes off-by-one errors visible immediately.
The Math class provides static methods for common calculations, and they are called on the class itself, as in Math.sqrt(16), not on an object. The most used are Math.abs for absolute value, Math.pow for powers, Math.sqrt for square roots, Math.max and Math.min, and Math.random, which returns a double in the range from 0, inclusive, to 1, exclusive. To get a random int in a range, the standard pattern is (int)(Math.random() * n) for a value from 0 to n − 1, and the cast must be applied after the multiplication — (int) Math.random() * n always gives 0, a classic trap.
The AP Java Quick Reference is a sheet of the classes and methods you are allowed to use on the exam, and you should learn to read it rather than memorize everything on it. It lists the String, Math, Integer, Double, ArrayList, and other classes with their methods and the exact signatures, and it is the authority on what is available: if a method is not on the sheet, do not use it in a free-response answer, because the marker may not accept it. Practise solving problems using only the methods on the reference, and check your method names and parameter types against it when you are unsure.
A char holds a single character, written in single quotes, as in 'A', while a String holds a sequence of characters in double quotes, and the two types are not interchangeable: "A" is a String of length one, not a char. Characters have numeric codes behind them, so 'A' + 1 is the int 66 in Java, though you will rarely use that fact directly. Special characters inside a String are written with escape sequences: \n for a new line, \t for a tab, \" for a double quote inside a double-quoted String, and \\ for a backslash itself. These small details matter when you build output strings, because a missing escape can turn a string literal into a compile-time error.
A worked example
Worked example: the code below extracts the first name from a full name and generates a random number from 1 to 6, like a die roll. Trace it carefully: indexOf finds the space, substring takes the characters before it, and the random expression is built in the right order.
String full = "Maya Patel";
int space = full.indexOf(" "); // 4
String first = full.substring(0, space); // "Maya"
int die = (int)(Math.random() * 6) + 1; // 1 to 6
System.out.println(first + " rolled " + die);
The space is at index 4, so substring(0, 4) gives the characters at indices 0 to 3, 'Maya'. Math.random() gives a double from 0 up to 1, multiplying by 6 gives 0 up to 6, the cast to int truncates to 0 to 5, and adding 1 gives 1 to 6. If the cast had been written as (int) Math.random() * 6, the cast would apply first, giving 0 every time. In your own code, write random-range expressions in this exact pattern and test the endpoints: the smallest and largest values it can produce.
Key Terms
- String
- An immutable sequence of characters, indexed from 0, with methods such as length, substring, and equals.
- Immutable
- Unable to be changed after creation; String methods return new Strings.
- substring(a, b)
- Returns the characters from index a up to, but not including, index b.
- indexOf
- Returns the first index of a substring, or −1 if it is not found.
- Math.random()
- Returns a double from 0, inclusive, to 1, exclusive.
- AP Java Quick Reference
- The official list of classes and methods available for use on the AP CSA exam.
Discussion Questions
- Why does substring(0, 4) on 'Maya Patel' give 'Maya' and not 'Maya '?
- A String is immutable. What does that mean for a method that seems to change one?
- Why is (int) Math.random() * 6 always 0?
Practice Questions
- String s = "Hello"; What is s.length() and s.charAt(1)?
- What does "Hello".substring(1, 3) return?
- What does "abc".indexOf("x") return?
- Write an expression giving a random int from 0 to 9.
- Why should you use equals rather than == to compare two Strings?
Show answers
- length 5; charAt(1) is 'e'.
- "el", the characters at indices 1 and 2.
- −1, because "x" is not in the String.
- (int)(Math.random() * 10)
- Because == compares references, while equals compares the characters the Strings contain.