AP Computer Science A

Java from the first line: objects and methods, selection and iteration, writing classes, then arrays, ArrayLists, 2D arrays, searching, sorting and recursion, unit by unit in the order of the AP Computer Science A course and exam description, every snippet traced line by line. Independent prep, not affiliated with or endorsed by the College Board.

Lessons

  1. From an algorithm to a running program: A program is an algorithm written in exact steps that run one at a time, and Java checks it twice, the compiler first for broken rules and then running it for crashes and wrong answers, so errors come in three kinds by when they show up.
  2. Variables and data types: A variable is a named, typed box, and the type fixes which values it can hold and what can be done with them, so int holds whole numbers, double real numbers and boolean true or false, while anything else is a reference type.
  3. Printing and string literals: println ends its line and print doesn't, and a string literal is text between double quotes in which a backslash starts an escape sequence, so a quote, a backslash or a new line can be put inside it.
  4. Arithmetic with int and double: The types of the two operands decide an arithmetic operation, so two ints give an int and 7 / 2 is 3 with remainder 7 % 2 equal to 1, while one double makes the whole operation decimal.
  5. Assignment, then input: An assignment works out the right side to one value first and only then stores it in the variable on the left, so x = x + 1 makes sense, and a variable needs a value before it is used.
  6. Casting and rounding: A cast converts on purpose, and (int) cuts off the fraction instead of rounding, so rounding a positive double means adding 0.5 before the cast, while an int widens to a double by itself.
  7. The limits of int and double: An int lives in 4 bytes, so past `Integer.MAX_VALUE` it wraps round to a negative number, and a double keeps only so many digits, so `0.1 + 0.2` is not exactly `0.3`.
  8. Compound assignment and ++: x += 5 is short for x = x + 5, so each compound operator does its arithmetic with the old value and stores the result, and x++ adds one the same way.
  9. Libraries, APIs and comments: Code we didn't write is used through its documentation, where an API lists what a class stores and what it can do, and a method's comments state its precondition, what must be true before the call, and its postcondition, what will be true after.
  10. Method signatures and calls: A method's signature is its name and the types of its parameters in order, so a call must match it, each argument copied into its parameter, and a non-void method's result has to be stored or used.
  11. Class methods and the Math class: A static method belongs to the class and is called on the class's name, and Math's are all static, each returning the type its signature gives, which is how Math.random() scaled and cast becomes a whole number in a chosen range.
  12. Objects, classes and constructors: A class is the blueprint and an object one thing built from it with new and a constructor whose parameter types match the arguments, and the variable holds a reference to the object, or null when there is none.
  13. Calling instance methods: An instance method is called on one object with the dot, so it works with that object's own data, and calling one through a null reference has no object to work on and throws a NullPointerException.
  14. Strings are objects that never change: A String is an immutable object, so concatenation with + builds a new String and leaves the old one alone, and anything joined to a String, a number or an object's toString, becomes text.
  15. String methods and indices: A String's characters are numbered from 0 to length() minus 1, so substring(a, b) takes the characters from a up to but not including b, and Strings are compared with equals and compareTo, never with ==.
  16. Choosing and repeating: Every algorithm is built from three things, steps in order, a choice between paths and a repeat of steps, and the choice and the repeat are each decided by a question with a true or false answer.
  17. Relational operators and boolean values: A relational operator compares two values and gives a boolean, true or false, and == compares primitive values but, on objects, only asks whether two references point at the same object.
  18. if and if-else: An if statement runs its body only when its condition is true, and an else gives the other path, so exactly one of the two runs, while the code after the whole statement runs either way.
  19. Nested ifs and else-if chains: In an if-else-if chain only the first true condition's branch runs, so the order of the conditions decides the result, and an inner if is only reached when the outer one let it in.
  20. And, or, not, and short-circuiting: && is true only when both sides are, || when at least one is, and ! flips a value, and Java stops as soon as the left side settles the answer, which is what lets a guard like x != 0 && 10 / x > 2 avoid dividing by zero.
  21. Equivalent boolean expressions: Two boolean expressions are equivalent when a truth table gives them the same value in every case, and De Morgan's laws turn a not over an and into an or of nots, and the other way round.
  22. while loops: A while loop checks its condition before every pass and runs its body while it holds, so something in the body has to move the condition towards false, or the loop never ends, and a test that is false at the start runs the body zero times.
  23. for loops: A for loop puts the start, the test and the update of a counter in one header, so it runs a counted number of times, and any for loop can be rewritten as a while loop with the same three parts.
  24. Standard loop algorithms: A few patterns cover most loop problems, a running total, a count of matches, a smallest or largest so far and peeling off digits with % 10 and / 10, and each one starts its variables before the loop and updates them inside it.
  25. Loops over a String: A loop over the indices 0 to length() minus 1 visits each character with substring(i, i + 1), which is how we count, find, reverse or rebuild text, and stopping one too late runs off the end of the String.
  26. Loops inside loops: An inner loop runs all the way through for every single pass of the outer loop, so the inner body runs the outer count times the inner count, and the inner loop can depend on the outer counter.
  27. Counting how often code runs: Run time can be compared without a clock by counting how many times a statement runs, and that count grows with the input, once per item for a single loop and about n times n for two nested loops over n items.
  28. Abstraction and program design: A good design starts from what the program must do and splits it into classes for the things involved and methods for the jobs, so each part can be used knowing only what it does, not how.
  29. Who a program affects: Software reaches people beyond its users, so its designers answer for its reliability, for the privacy and fairness of what it does with people's data, and for using other people's code only as its licence allows.
  30. The anatomy of a class: A class declares private instance variables, the data each object keeps, and public methods, what other code may ask of it, so the object's data can only be changed in the ways the class allows.
  31. Writing constructors: A constructor has the class's name and no return type, and its job is to give every instance variable its starting value, from its parameters or a default, with Java filling in 0, false or null for any it skips.
  32. Writing methods: A method's header promises a return type and parameters, a non-void method must return a value of that type on every path, and a void method changes the object or prints instead, with accessors reading data and mutators changing it.
  33. Passing and returning objects: A parameter of a class type receives a copy of the reference, not of the object, so a method can change the object the caller sees but can't make the caller's variable point somewhere else.
  34. Static variables and methods: A static variable belongs to the class, so there is one copy shared by every object, and a static method runs with no object at all, so it can't use instance variables.
  35. Scope and access: A local variable lives only inside the block that declares it, and a parameter or local with the same name as an instance variable hides it there, while private limits who can use a member to code inside its own class.
  36. The this keyword: Inside a method or constructor, this is the object it was called on, so this.name is the instance variable even when a parameter shares its name, and this can be passed to give another method the current object.
  37. Data sets and their people: A data set is a collection of values that a program can search for patterns, and because it often describes people, how it was collected, how it is kept and what it leaves out decide whether its conclusions are fair.
  38. Arrays: An array is a fixed number of values of one type in numbered places from 0 to length minus 1, made with new and filled with 0, false or null until set, and an index outside that range throws an exception.
  39. Traversing an array: An indexed for loop from 0 while i is less than length visits every element and can change it, while an enhanced for loop hands over a copy of each element, so it can read the array but not replace what's in it.
  40. Array algorithms: The standard array algorithms, a sum or average, a smallest or largest, a count, a check that some or all elements pass, neighbouring pairs, shifting and reversing, are each one traversal with the right variables set up before it.
  41. Reading a text file: A Scanner on a File reads a text file a token or a line at a time, hasNext asking whether anything is left, so a while loop reads exactly as much as the file holds, and a missing file has to be declared with throws IOException.
  42. Integer and Double: Integer and Double wrap a primitive value in an object so it can go where only objects can, and Java boxes and unboxes between the two by itself, which is how an ArrayList of Integer can hold numbers.
  43. ArrayList methods: An ArrayList grows and shrinks as elements are added and removed, and add, get, set, remove and size work by index, with add and remove shifting every later element along one place.
  44. Traversing an ArrayList: An ArrayList is traversed with an indexed loop to size(), and removing while going forwards skips the next element, so a loop that removes must go backwards or not step on after a removal, and an enhanced for loop can't add or remove at all.
  45. 2D arrays: A 2D array is an array of rows, each row an array, so grid[r][c] is row r and column c, grid.length counts the rows and grid[0].length the columns.
  46. Traversing a 2D array: Nested loops visit every element of a 2D array, and the outer loop decides the order, rows on the outside for row-major order and columns on the outside for column-major order.
  47. 2D array algorithms: The one-dimensional algorithms work on a 2D array along one row, one column or the whole grid, by fixing one index and looping the other, or by nesting the two loops.
  48. Linear search and binary search: A linear search checks the elements one by one and stops at the first match, so it can take all n looks, while binary search needs sorted data and looks at the middle first, throwing away half of what's left each time, so it takes about log n looks.
  49. Selection sort and insertion sort: Selection sort swaps the smallest remaining element into the next place, and insertion sort slides each element left into the sorted part before it, so after k passes either way the first k places are in order.
  50. Recursion: A recursive method calls itself on a smaller case and stops at a base case, each call waiting with its own parameters until the one it made returns, so a missing base case recurses until the stack runs out.
  51. Merge sort: Merge sort splits an array in half again and again until each piece has one element, then merges pairs of sorted pieces back into larger sorted ones, the whole job done by a method that calls itself on each half.