AP Computer Science A
Advanced Placement Computer Science A covering object-oriented programming in Java, equivalent to a first-semester college course. Topics include primitive types, classes, control flow, arrays, ArrayLists, 2D arrays, inheritance, polymorphism, and recursion.
Ämne: Teknik · Nivå: Gymnasium (16–19) · 429 kort
Innehåll
- Java's three main primitive types tested on AP CS A are int (whole numbers, 32-bit), double (decimals, 64-bit floating point), and boolean (true/false). Strings are NOT primitive — String is a class.
- Variable declaration in Java: type name = value; — e.g. int x = 5; double pi = 3.14; boolean isReady = true; String s = "hi"; Each statement ends with a semicolon.
- Integer division in Java: when both operands are int, the result is int — the decimal is truncated (not rounded). 5/2 = 2, not 2.5. To get 2.5, at least one operand must be double: 5.0/2 or (double)5/2.
- Modulo operator % returns the remainder after integer division. 17 % 5 = 2 (since 17 = 3*5 + 2). Useful for checking divisibility: x % 2 == 0 means x is even.
- Operator precedence in Java (highest first): parentheses (), unary minus and !, multiplication/division/modulo (* / %), addition/subtraction (+ -), relational (< > <= >=), equality (== !=), logical AND (&&), logical OR (||), assignment (=).
- Casting in Java: (int) 3.7 truncates the decimal and gives 3 (NOT 4 — Java truncates toward zero, it does not round). (double) 5 promotes int 5 to double 5.0.
- Compound assignment operators in Java combine an operation with assignment: x += 3 means x = x + 3. Other forms: -=, *=, /=, %=. Also ++ (increment by 1) and -- (decrement by 1).
- Integer.MAX_VALUE is the largest int Java can hold: 2147483647 (about 2.1 billion). Integer.MIN_VALUE is -2147483648. Adding 1 to MAX_VALUE causes overflow and wraps to MIN_VALUE.
- Mixed-type arithmetic in Java: if either operand is a double, the result is a double. int + double → double. So 3 + 2.0 = 5.0, but 3 + 2 = 5 (int).
- Java is strongly typed and statically typed: you must declare a variable's type at compile time, and the type cannot change. int x = 5; later x = "hi"; is a compile error.
- String is a class in Java, not a primitive. Strings are immutable — once created they cannot be changed. Methods like .substring() and .toLowerCase() return a NEW String, leaving the original unchanged.
- String.length() returns the number of characters as an int. "hello".length() = 5. Note: length() is a method on Strings (with parens), but length is a field on arrays (no parens).
- String.substring(int start) returns the substring from index start to the end. "hello".substring(2) = "llo". String indexing is zero-based.
- String.substring(int start, int end) returns chars from index start up to but NOT including end. "hello".substring(1, 4) = "ell" — indexes 1, 2, 3. The end bound is exclusive.
- String.indexOf(String s) returns the index of the first occurrence of s, or -1 if not found. "hello".indexOf("l") = 2. "hello".indexOf("z") = -1.
- String.equals(String other) returns true if two strings have the same characters in the same order. Always use .equals() to compare String content — NEVER ==, which compares references (memory addresses), not content.
- String.compareTo(String other) returns a negative int if this < other, 0 if equal, positive if this > other (lexicographic / dictionary order). "apple".compareTo("banana") is negative; "b".compareTo("a") is positive.
- String concatenation in Java uses + : "Hi " + "there" = "Hi there". If either operand is a String, the other is converted to String automatically: "x=" + 5 = "x=5".
- Math.abs(x) returns the absolute value of x. Math.abs(-5) = 5. Works for both int and double. Math.abs(-3.7) = 3.7.
- Math.pow(base, exponent) returns base raised to the exponent as a double. Math.pow(2, 3) = 8.0. Both arguments and return type are double, so cast to int if you need int: (int) Math.pow(2, 3).
- Math.sqrt(x) returns the square root of x as a double. Math.sqrt(25) = 5.0. Math.sqrt(2) ≈ 1.414. Argument should be non-negative; otherwise returns NaN.
- Math.random() returns a random double in the range [0.0, 1.0) — 0 inclusive, 1 exclusive. To get a random int from 0 to n-1: (int) (Math.random() * n). For 1 to n: (int) (Math.random() * n) + 1.
- Integer and Double are wrapper classes that wrap the primitive types int and double as objects. They have static constants like Integer.MAX_VALUE and parser methods like Integer.parseInt("42") which returns 42.
- Autoboxing automatically converts a primitive (int) to its wrapper object (Integer) when needed; unboxing does the reverse. Integer x = 5; (autobox). int y = x; (unbox). Tested mostly with ArrayList<Integer>.
- Dot notation calls a method on an object: objectRef.methodName(arguments). For example, s.length() calls length() on the String referenced by s. Static methods use the class name: Math.sqrt(4).
- Integer.parseInt(String s) converts a string of digits into an int. Integer.parseInt("42") = 42. Double.parseDouble("3.14") = 3.14. Throws NumberFormatException if the string isn't a valid number.
- String.charAt(int i) returns the character at index i as a char. "hello".charAt(1) = 'e'. Throws StringIndexOutOfBoundsException if i is negative or >= length().
- An object reference variable stores the memory address of an object, not the object itself. String s = "hi"; means s holds a reference to the String. Two reference variables can point to the same object.
- The keyword null represents a reference that points to no object. A NullPointerException is thrown if you try to call a method on null: String s = null; s.length(); will crash.
- A method with no return value uses void as its return type: public void printName() { ... }. A method that returns a value must specify its type: public int getAge() { return age; }.
- Relational operators return a boolean: < (less than), > (greater than), <= (less or equal), >= (greater or equal), == (equal), != (not equal). Use them only on numeric types for == / != — not on Strings.
- Logical operators in Java: && (AND), || (OR), ! (NOT). All return boolean. (x > 0 && x < 10) is true if x is between 1 and 9 inclusive.
- Short-circuit evaluation: in A && B, if A is false, B is never evaluated (whole expression is false anyway). In A || B, if A is true, B is never evaluated. Useful to guard against errors: if (s != null && s.length() > 0).
- De Morgan's laws: !(A && B) is equivalent to !A || !B. !(A || B) is equivalent to !A && !B. Used to simplify or rewrite complex boolean expressions.
- if statement syntax: if (condition) { statements } The condition must be a boolean expression. Curly braces are optional for a single statement but recommended for clarity.
- if/else if/else: only one branch will execute — the FIRST branch whose condition is true. The else block (if any) catches anything that didn't match. Order matters when ranges overlap.
- Nested if: an if inside another if. Use when later checks only make sense after the first is true. if (x > 0) { if (x < 100) { ... } } is equivalent to if (x > 0 && x < 100).
- A boolean variable can be used directly in an if: if (isReady) { ... } is equivalent to if (isReady == true). Avoid the redundant == true — it's a code smell.
- Two boolean expressions are equivalent if they produce the same value for every combination of inputs. Use a truth table to verify. Example: !(a && b) and !a || !b have the same truth table.
- Comparing doubles with == is risky due to floating-point round-off. Prefer Math.abs(a - b) < 0.0001 to check if two doubles are approximately equal. For ints, == is fine.
- while loop syntax: while (condition) { body } The body repeats as long as the condition is true. The condition is checked BEFORE each iteration, so the body might run zero times.
- for loop syntax: for (init; condition; update) { body }. Example: for (int i = 0; i < 10; i++) { ... } runs 10 times with i = 0 through 9.
- Enhanced for-each loop: for (type var : collection) { body }. Example: for (int x : arr) { sum += x; } iterates over each element. Cannot modify the array via the loop variable.
- Off-by-one error: a loop runs one too many or one too few times, often from mixing < and <=. for (int i = 0; i <= n; i++) runs n+1 times (i = 0..n). To run exactly n times, use i < n.
- An infinite loop runs forever because the condition never becomes false. Common cause: forgetting to update the loop variable. while (i < 10) { sum += i; } without i++ never ends.
- Nested loops: a loop inside a loop. The inner loop runs completely for each iteration of the outer. A 3x4 nested loop runs the inner body 12 times. Used for 2D arrays and combinatorics.
- String traversal with a for loop: for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); ... }. Each character is at a unique index 0 through length()-1.
- A loop invariant is a condition that is true before and after each iteration of a loop. Used for proving correctness. Example: after iteration k, sum equals the sum of the first k elements.
- Algorithm analysis: count iterations as a function of input size n. Single loop over n: n iterations. Nested loops both over n: n*n = n² iterations. Used to compare efficiency.
- Decrementing for loop: for (int i = n - 1; i >= 0; i--) iterates from n-1 down to 0. Used when iterating backward through a String or array (e.g., to reverse).