AP CS A Review 2013
AP CS A Review 2013
NOTE: Sections that are not considered part of the Java Subset for the AP CS exam are not included in these pages, for example Scanners. Taken from the UW 143 Review Building Java Programs: Ch. 1-10
Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 1-10 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ )
Copyright 2008 by Pearson Education
List of Items not included in the AP CS exam, but we covered in class to build projects.
So these items are not included in these pages
char: Chapter 4.4 Scanners Drawing Panel & Graphics Random Class (5.1) Reading Files (6.1) Input Tokens (6.2) Output to Files (6.4) PrintStream
System.out.println
A statement that prints a line of output on the console.
pronounced "print-linn" sometimes called a "println statement" for short
class method A statement statement statement method B statement statement method C statement statement statement
5
procedural decomposition:
n n
Declaring a method
Gives your method a name so it can be executed
Syntax:
public static void name() { statement; statement; ... statement; }
Example:
public static void printWarning() {
System.out.println("This product causes cancer"); System.out.println("in lab rats and humans.");
}
Copyright 2008 by Pearson Education
Calling a method
Executes the method's code
Syntax:
name();
You can call the same method many times if you like.
Example:
printWarning();
Output:
Control flow
When a method is called, the program's execution... "jumps" into that method, executing its statements, then "jumps" back to the point where the method was called.
public class MethodsExample { public static void main(String[] args) { public static void message1() { message1(); System.out.println("This is message1.");
}
message2();
Name
int double char boolean
Examples 42, -3, 0, 926394 3.1, -0.25, 9.4e3 'a', 'X', '?', '\n' true, false
Expressions
expression: A value or operation that computes a value.
Examples:
1 + 4 * 5 (7 + 2) * 6 / 3 42
The simplest expression is a literal value. A complex expression can use operators and parentheses.
10
11
is 2 is 3
43 5 ) 218 20 18 15 3
3 4 ) 14 12 2
Applications of % operator:
Obtain last digit of a number: Obtain last 4 digits: See whether a number is odd:
Precedence
precedence: Order in which operators are evaluated. Generally operators evaluate left-to-right. 1 - 2 - 3 is (1 - 2) - 3 which is -4
But */% have a higher level of precedence than +-
1 + 3 * 4 6 + 8 / 2 * 3 6 + 4 * 3 6 + 12
is 13
is 18
(1 + 3) * 4 1+3 * 4-2
Copyright 2008 by Pearson Education
is 16 is 11
13
String concatenation
string concatenation: Using + between a string and
Variables (2.2)
variable: A piece of the computer's memory that is given a
14
myGPA
3.95
15
Type casting
type cast: A conversion from one type to another. To promote an int into a double to get exact division from / To truncate a double from a real number to an integer
Syntax:
(type) expression Examples: double result = (double) 19 / 5; int result2 = (int) result; int x = (int) Math.pow(10, 3);
// 3.8 // 3 // 1000
16
17
Integer methods
intValue(value) Integer.MIN_VALUE Integer.MAX_VALUE Integer(value) Returns value as an int A constant holding the minimum value an int can have A constant holding the maximum value an int can have Constructs a newly allocated Integer object that represents the specified int value.
Part of the java.lang.Integer NOTE: these are the only List methods used in the AP CS Exam.
18
Modify-and-assign operators
shortcuts (NOT REQUIRED for AP CS A)
Shorthand variable += variable -= variable *= variable /= variable %= x += 3; gpa -= 0.5; number *= 2; value; value; value; value; value; Equivalent longer version variable = variable + value; variable = variable - value; variable = variable * value; variable = variable / value; variable = variable % value; // x = x + 3; // gpa = gpa - 0.5; // number = number * 2;
19
Check if the test is true. If not, stop. Execute the statements. Perform the update.
20
System.out.print
Prints without moving to a new line allows you to print partial messages on the same line
int highestTemp = 5; for (int i = -3; i <= highestTemp / 2; i++) { System.out.print((i * 1.8 + 32) + " "); }
Output:
26.6
28.4
30.2
32.0
33.8
35.6
21
Nested loops
nested loop: A loop placed inside another loop.
for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5; j++) { System.out.print((i * j) + "\t"); } System.out.println(); // to end the line }
Output:
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20
Statements in the outer loop's body are executed 4 times. The inner loop prints 5 numbers each time it is run.
Copyright 2008 by Pearson Education
22
Variable scope
scope: The part of a program where a variable exists. From its declaration to the end of the { } braces
A variable declared in a for loop exists only in that loop. A variable declared in a method exists only in that method.
public static void example() { int x = 3; for (int i = 1; i <= 10; i++) { System.out.println(x); } // i no longer exists here } // x ceases to exist here
i's scope
x's scope
23
public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE = 3.5; public static final int SSN = 658234569;
24
Parameters (3.1)
parameter: A value passed to a method by its caller.
Instead of lineOf7, lineOf13, write line to draw any length.
When declaring the method, we will state that it requires a parameter for the number of stars. When calling the method, we will specify how many stars to draw.
main
7 13
line line
******* *************
25
Passing parameters
Declaration: public static void name (type name, ..., type name) { statement(s); } Call: methodName (value, value, ..., value); Example: public static void main(String[] args) { sayPassword(42); // The password is: 42 sayPassword(12345); // The password is: 12345 }
public static void sayPassword(int code) { System.out.println("The password is: " + code); }
26
These are the only Math Methods required for the AP CS, others can be used for the Free Response Questions (FRQ), but will not be in the Multiple Choice.
27
Return (3.2)
return: To send out a value as the result of a method.
The opposite of a parameter:
Parameters send information in from the caller to the method. Return values send information out from a method to its caller.
Math.abs(42)
Math.round(2.71)
28
Returning a value
public static type name(parameters) { statements; ... return expression; }
Example:
// Returns the slope public static double double dy = y2 double dx = x2 return dy / dx; } of the line between the given points. slope(int x1, int y1, int x2, int y2) { y1; x1;
29
more different methods with the same name but different number and/or type of parameters.
public static void drawBox() { // no parameters // has code that creates a standard sized box ... } public static void drawBox(int height, int width) { // code that draws the box based on the height and // width parameter values ... } Which method used is based on how it is called: drawBox(); // uses the first drawBox method drawBox(10,20); // uses second drawBox method
Copyright 2008 by Pearson Education
30
Strings (3.3)
string: An object storing a sequence of text characters. String name = "text"; String name = expression;
Characters of a string are numbered with 0-based indexes:
The first character's index is always 0 The last character's index is 1 less than the string's length The individual characters are values of type char
Copyright 2008 by Pearson Education
31
String methods
Method name indexOf(str) length() substring(index1, index2) or substring(index1) compareTo(String other) Description index where the start of the given string appears in this string (-1 if it is not there) number of characters in this string the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 omitted, grabs till end of string returns <0 if this is less than other returns 0 if this is equal to other returns >0 if this is greater than other
Note: These are the only String methods required for the AP CS...
Copyright 2008 by Pearson Education
32
33
Key idea:
Cumulative sum variables must be declared outside the loops
that update them, so that they will exist after the loop.
34
if/else (4.2)
Executes one block if a test is true, another if false
if (test) { statement(s); } else { statement(s); }
Example:
double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); } else { System.out.println("Application denied."); }
Copyright 2008 by Pearson Education
35
Relational expressions
A test in an if is the same as in a for loop.
for (int i = 1; i <= 10; i++) { ... if (i <= 10) { ...
These are boolean expressions, seen in Ch. 5.
!(2 == 3)
p true
!p false
false false
false true
false true
boolean minor = (age < 21); boolean expensive = iPhonePrice > 200.00; boolean iLoveCS = true; if (minor) { System.out.println("Can't purchase alcohol!"); } if (iLoveCS || !expensive) { System.out.println("Buying an iPhone"); }
Copyright 2008 by Pearson Education
38
De Morgan's Law
De Morgan's Law:
!a || !b !a && !b
if/else Structures
Exactly 1 path: (mutually exclusive)
if (test) { statement(s); } else if (test) { statement(s); } else { statement(s); } if (test) { statement(s); } if (test) { statement(s); } if (test) { statement(s); }
Copyright 2008 by Pearson Education
0 or 1 path:
if (test) { statement(s); } else if (test) { statement(s); } else if (test) { statement(s); }
40
Add a statement outside the loop to place the initial "post." Also called a fencepost loop or a "loop-and-a-half" solution. Algorithm template:
place a post. for (length of fence - 1) { place some wire. place a post. }
41
should print:
1, 2, 3, 4, 5
Solution: public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line }
Copyright 2008 by Pearson Education
42
Example: int num = 1; while (num <= 200) { System.out.print(num + " "); num = num * 2; }
OUTPUT:
1 2 4 8 16 32 64 128
Copyright 2008 by Pearson Education
43
// prompt until the user gets the right password String phrase; do { System.out.print("Password: "); phrase = console.next(); } while (!phrase.equals("abracadabra"));
44
"Boolean Zen"
Students new to boolean often test if a result is true:
if (bothOdd(7, 13) == true) { ... } // bad
// bad // good
45
public static boolean bothOdd(int n1, int n2) { if (n1 % 2 != 0 && n2 % 2 != 0) { return true; } else { return false; } }
Observation: The if/else is unnecessary. Our logical test is itself a boolean value; so return that!
public static boolean bothOdd(int n1, int n2) { return (n1 % 2 != 0 && n2 % 2 != 0); }
Copyright 2008 by Pearson Education
46
public class ReadFile { public static void main(String[] args) throws FileNotFoundException {
Like saying, "I hereby announce that this method might throw
47
Arrays (7.1)
array: object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array.
index
2 -2
3 26
4 5
5 17
6 -6
9 3
value 12 49
84 72
element 0
element 4
element 9
48
Array declaration
type[] name = new type[length];
Example:
index value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
49
Accessing elements
name[index] name[index] = value;
Example:
// access // modify
numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); } index 0 1 0 2 0 3 -6 0 4 0 5 0 6 0 7 0 8 0 9 0
50
value 27 0
Out-of-bounds
Legal indexes: between 0 and the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(data[0]); System.out.println(data[9]); System.out.println(data[-1]); System.out.println(data[10]);
index value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0
// // // //
51
52
index
2 -2
3 26
4 5
5 17
6 -6
value 12 49
Useful when you know what the array's elements will be. The compiler figures out the size by counting the values.
53
Description
binarySearch(array, value) returns the index of the given value in a sorted array (< 0 if not found) equals(array1, array2) returns true if the two arrays contain the same elements in the same order sets every element in the array to have the given value arranges the elements in the array into ascending order returns a string representing the array, such as "[10, 30, 17]"
54
Arrays as parameters
Declaration: public static type methodName(type[] name) {
Example:
Call: methodName(arrayName);
Example:
int[] scores = {13, 17, 12, 15, 11}; double avg = average(scores);
Copyright 2008 by Pearson Education
55
Arrays as return
Declaring: public static type[] methodName(parameters) {
Example:
public static int[] countDigits(int n) { int[] counts = new int[10]; ... return counts; }
56
its value is copied. Modifying the value of one variable does not affect others. int int y = x = x = 5; y = x; 17; 8;
// x = 5, y = 5 // x = 5, y = 17 // x = 8, y = 17
x y
57
is not copied; both variables refer to the same object. Modifying the value of one variable will affect others.
int[] a1 = {4, 5, 2, 12, 14, 14, 9}; int[] a2 = a1; // refer to same array as a1 a2[0] = 7; System.out.println(a1[0]); // 7 a1 a2
Copyright 2008 by Pearson Education
index value
0 7 4
1 5
2 2
6 9
58
12 14 14
Null
null : A reference that does not refer to any object.
Fields of an object that refer to objects are initialized to null. The elements of an array of objects are initialized to null.
String[] words = new String[5]; DrawingPanel[] windows = new DrawingPanel[3]; index words 0 1 2 3 4
windows
It is illegal to dereference null (causes an exception). null is not any object, so it has no methods or data.
String[] words = new String[5]; System.out.println("word is: " + words[0]); words[0] = words[0].toUpperCase(); Output: word is: null Exception in thread "main" java.lang.NullPointerException at Example.main(Example.java:8)
Copyright 2008 by Pearson Education
60
DrawingPanel objects.
object: An entity that combines state and behavior. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects.
61
Fields (8.2)
field: A variable inside an object that is part of its state. Each object has its own copy of each field. encapsulation: Declaring fields private to hide their data. With few exceptions ALWAYS Make fields private in Objects. Declaration syntax:
private type name;
Example:
62
Instance methods
instance method: One that exists inside each object of a
63
A Point class
public class Point { private int x; private int y; // Changes the location of this Point object. public void draw(Graphics g) { g.fillOval(x, y, 3, 3); g.drawString("(" + x + ", " + y + ")", x, y); } }
Each Point object contains data fields named x and y. Each Point object contains a method named draw that draws
64
We say that it executes in the context of a particular object. draw can refer to the x and y of the object it was called on.
65
Kinds of methods
Instance methods take advantage of an object's state. Some methods allow clients to access/modify its state. accessor: A method that lets clients examine object state. Example: A distanceFromOrigin method that tells how far a Point is away from (0, 0). Accessors often have a non-void return type. mutator: A method that modifies an object's state. Example: A translate method that shifts the position of a Point by a given amount.
66
Constructors (8.4)
constructor: Initializes the state of new objects.
public type(parameters) { statements; }
Example:
67
called when an object is printed/concatenated to a String: Point p1 = new Point(7, 2); System.out.println("p1: " + p1); Every class has a toString, even if it isn't in your code.
Default is class's name and a hex number: Point@9e8c34
Copyright 2008 by Pearson Education
68
this.field
To call a method:
this.method(parameters);
To call a constructor from another constructor:
this(parameters);
69
Static methods
static method: Part of a class, not part of an object. shared by all objects of that class
good for code related to a class but not to each object's state does not understand the implicit parameter, this;
Declaration syntax:
public static type name(parameters) { statements; }
70
Inheritance (9.1)
inheritance: A way to form new classes based on existing
One class can extend another, absorbing its data/behavior. superclass: The parent class that is being extended. subclass: The child class that extends the superclass and inherits its behavior.
71
By extending Employee, each Secretary object now: receives a getHours, getSalary, getVacationDays, and getVacationForm method automatically
can be treated as an Employee by client code (seen later)
72
public class Secretary extends Employee { // overrides getVacationForm in Employee class public String getVacationForm() { return "pink"; } ... }
73
public class LegalSecretary extends Secretary { public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + 5000.0; } ... }
74
Abstract Class
Abstract Class: A Java Class that cannot be instantiated, but that instead serves
Abstract classes are useful when a superclass doesn t correspond to a real thing
but more of an idea abstract classes can t be instantiated (no new) they can have fields they can have concrete methods they generally have abstract methods
public abstract class name { private <type> name; // can have fields //can have abstract and/or concrete methods... public type name(type name, ..., type name); public type name(type name, ..., type name){ ... // statements of method } }
Copyright 2008 by Pearson Education
75
Interfaces
interface: A list of abstract methods that a class can implement.
Interfaces give you an is-a relationship without code sharing.
public interface name { public type name(type name, ..., type name); public type name(type name, ..., type name); ... } Example: public interface Vehicle { public double speed(); public void setDirection(int direction); }
76
Implementing an interface
public class name implements interface { ... }
Example:
An Abstract Class can implement an interface public abstract class name implements interface_name { ... }
Copyright 2008 by Pearson Education
77
Polymorphism
polymorphism: Ability for the same code to be used with
// 55000.0 // pink
78
Lists (10.1)
list: a collection storing an ordered sequence of elements each element is accessible by a 0-based index a list has a size (number of elements that have been added) elements can be added to the front, back, or elsewhere in Java, a list can be represented as an ArrayList object
79
Idea of a list
Rather than creating an array of boxes, create an object
[]
You can add items to the list. The default behavior is to add to the end of the list.
[hello, ABC, goodbye, okay]
The list object keeps track of the element values that have
been added to it, their order, indexes, and its total size.
Think of an "array list" as an automatically resizing array
object. Internally, the list is implemented using an array and a size field.
80
types.
81