AP Computer Science A · Unit 1 lecture · Part 11 of 11 · 9 min

Unit 1 wrap-upPut it together

Mr. Thompkins
That's the whole unit. Let's step back. Every topic you learned answers one of two questions: what value does this produce, and what type is it? Keep asking those two questions and Unit 1 questions stop being tricky.
TopicThe one thing to remember
Errors (1.1)Compiling proves only that the rules were followed
Types (1.2)int, double, boolean hold values; String and objects hold references
Expressions (1.3)int / int drops the decimals; a String makes + glue
Casting (1.5)(int) chops toward zero; int overflows silently
Methods (1.7-1.11)Match the signature; use what non-void methods return
Objects (1.12-1.14)new makes an object; = copies the arrow, not the object
Strings (1.15)Indexes 0 to length() - 1; substring stops before the end index
Unit 1 on one page.
?Wait, what's the difference between a class method and an instance method again?
A class method has static in its header and is called on the class name, like Math.sqrt(9). An instance method has no static and is called on an object, like a.getMl(). Instance methods work with that object's own data.

Three threads run through this unit. First, types decide behavior: int / int truncates, a String turns + into glue, and a method's return type decides where its call can go. Second, evaluation is mechanical: Java works through every expression in a fixed order, so you can always trace it step by step. Third, variables of class types hold arrows: new makes an object, = copies arrows, and Strings never change, they get replaced.

Pause and think
Connect two topics: why is s.substring(1); on its own line a logic error, while a.add(5); on its own line is fine?
I thought about it. Show me
Strings are immutable, so substring doesn't change s. It returns a new String, and a call on its own line throws that value away, so nothing happens. add is a void method on a mutable object: its whole job is to change the object, so calling it as a statement is exactly right.

Traps that cost points

✕ Expecting 7 / 2 to be 3.5.
✓ Both are ints, so it's 3. Use 7 / 2.0 or (double) 7 / 2.
✕ Thinking (int) rounds.
✓ It truncates toward zero. (int) 9.99 is 9. Round with (int) (x + 0.5).
✕ Reading 1 + 2 + "3" as "123".
✓ Left to right: 1 + 2 is 3 first, so the result is "33".
✕ Storing the result of a void method.
✓ void returns nothing. Call it as a statement.
✕ (int) Math.random() * 6 + 1 for a die roll.
✓ That's always 1. Cast the whole product: (int) (Math.random() * 6) + 1.
✕ Thinking b = a; copies an object.
✓ It copies the reference. a and b are aliases of one object.
✕ Calling s.substring(2); and expecting s to change.
✓ Strings are immutable. Write s = s.substring(2);.
✕ Including the end index in substring(a, b).
✓ It stops before b. The length is b - a.
✕ Comparing Strings with ==.
✓ Use equals for contents, compareTo for order.

Unit 1 syntax sheet

7 / 2 7 % 2 7 / 2.0
Integer division, remainder, double division3, 1 and 3.5
(double) a / b
Cast first, then divideKeeps the decimals of an int division
(int) (x + 0.5)
Round a nonnegative doubleCast alone truncates
x += 3; x++;
Compound assignment, add oneSame as x = x + 3; and x = x + 1;
Integer.MAX_VALUE
Largest int, 2147483647One more overflows to Integer.MIN_VALUE
Math.abs(x) Math.pow(b, e) Math.sqrt(x)
Absolute value, power, square rootpow and sqrt return double
(int) (Math.random() * (max - min + 1)) + min
Random int from min to maxInclusive at both ends
Bottle b = new Bottle(500);
Create an objectArguments must match a constructor
b.add(5); int n = b.getMl();
Call a void and a non-void methodUse what non-void methods return
s.length() s.indexOf(t)
Number of characters; first index of t or -1Last index is length() - 1
s.substring(a, b) s.substring(a)
From a up to, not including, b; from a to the endLength of the first is b - a
s.equals(t) s.compareTo(t) < 0
Same characters; s comes before tCase-sensitive; capitals sort first

FRQ strategy for Unit 1

  1. Unit 1 lives mostly in Question 1, Methods and Control Structures (7 points). Part B usually works with Strings, so the String methods have to be automatic.
  2. Read the method header first: its return type, its parameters, and whether it's static. Return that type on every path, and return it, don't print it.
  3. When the question says to call a given method, call it with the right arguments and use what it returns. Rewriting its logic yourself loses that point.
  4. Check every division: do you want an int or a double? Check every substring against the shortest String the preconditions allow.
  5. Use only Quick Reference methods. Never hard-code an index that depends on the data: find it with indexOf or length().
  6. On multiple choice, trace with a pencil: number String letters from 0, keep a trace table for variables, and draw arrows for objects.
Mixed FRQ practice
Write a static method username(String first, String last, int year) that returns a username made of the first letter of first, the first four letters of last, and the last two digits of year, always as two digits. Precondition: last has at least 4 letters and year is between 2000 and 2099. Examples: username("Maria", "Lopez", 2027) returns "MLope27", and username("Ken", "Adams", 2009) returns "KAdam09".
  1. The first letter of first is first.substring(0, 1). The first four letters of last are last.substring(0, 4).
    Why?
    substring(0, 4) takes indexes 0 to 3: four characters. The precondition promises last is long enough, so no check is needed.
  2. The last two digits of year are year % 100: 27 for 2027, but 9 for 2009. Concatenating 9 would give "KAdam9", one digit short.
    Why?
    This is the trap the examples are warning you about. Always test the example that looks unusual.
  3. Trick: add 100 first. year % 100 + 100 is between 100 and 199, so it always has three digits: 127 or 109. Turn it into a String and drop the 1 with substring(1): "27" or "09".
    Why?
    "" + number makes a String from a number. substring(1) skips index 0, the leading 1.
  4. Glue the three pieces and return the result (don't print it).

Answer:

public static String username(String first, String last, int year)
{
    String yy = "" + (year % 100 + 100);
    return first.substring(0, 1) + last.substring(0, 4)
        + yy.substring(1);
}

username("Maria", "Lopez", 2027) returns "MLope27" and username("Ken", "Adams", 2009) returns "KAdam09" (checked under Java 17).

Stuck? Get a hint
  1. Build the answer in three pieces: one letter, four letters, two digits.
  2. year % 100 gives the last two digits, but as a number. What goes wrong for 2009?
  3. Try year % 100 + 100, then turn it into a String and take substring(1).
Check yourself
What is printed?
String s = "Toledo";
System.out.println(s.substring(0, 1) + (s.length() - 1));
  1. AT5
  2. BTod5
  3. CT4
  4. DTdo5
Show the answer

A. s.length() is 6, and the parentheses make s.length() - 1 happen first: 5. substring(0, 1) is "T", and "T" + 5 is "T5". Without the parentheses, "T" + 6 would be glued first, and subtracting 1 from a String doesn't compile. Choice C forgets that "Toledo" has 6 letters.

Check yourself
What is printed?
Bottle x = new Bottle(10);
Bottle y = x;
y.add(5);
System.out.println(x.getMl() + " " + y.fractionFull());
  1. A5 0.5
  2. B5 0.0
  3. C0 0.5
  4. D10 1.0
Show the answer

A. One new, so x and y are aliases of the same object, which starts at 0 ml. y.add(5) changes that object to 5 ml, so x.getMl() is 5. fractionFull casts ml to double before dividing: 5.0 / 10 is 0.5. Choice C treats y as a separate bottle, and choice B forgets the cast inside fractionFull.

Mr. Thompkins
That's Unit 1. Go test it while it's fresh: take the Unit 1 quiz, and every time you miss one, come back to that section and open its recall cards. See you in Unit 2, where your programs start making decisions and repeating work.