AP CSA Study Guide - AP Practice
AP CSA Study Guide - AP Practice
AP Computer Science A
Exam Date: Friday, May 15, 2020
Table of Contents
Click on the topic you want to learn about in the table of contents and click on the link which will take
you to the page it is on.
AP Computer Science A 1
Table of Contents 2
Unit 4: Iteration 24
4.1 While Loops 25
4.2 For Loops 25
4.3 Developing Algorithms Using Strings 26
4.4 Nested Iteration 26
4.5 Informal Code Analysis 26
Unit 7: ArrayList 37
7.1 Introduction to ArrayList 37
7.2 ArrayList Methods 38
The Methods of List<E> 39
7.3 Traversing ArrayLists 40
7.4 Developing Algorithms Using ArrayLists 41
7.5 Searching 41
7.6 Sorting 42
Scanner class: 43
Reference Sheet 44
S.O.P. vs S.O.P.ln:
System.out.print(“Hello World”); //prints out “Hello World” on line 1
System.out.println(“Hello World 2”); //still prints out “Hello World 2” on line 1, but now moves
the cursor to line 2
System.out.print(“Hello World 3”); //now prints out “Hello World 3” on line 2
Int:
Integers, no decimals
Ex: int price = 1;
Boolean-:
Either “true” or “false”
boolean yes = “true”;
Double:
Similar to int, but now with decimals
double price = 1.0;
1.5: Casting and Ranges of Variables (Implicit and Explicit Type Casting)
Making a variable behave as a variable of another type
You can never cast to and from booleans (and later to and from objects like Strings)
No need to cast from an int to a double if a double is already included in the expression, automatically
done. This is referred to as implicit type casting.
double bob = 1 + 2.0 //results in a double (3.0)
Not possible to cast from an int to a double if no double exists in the expression (less to more
complicated)
double bob = 1 + 1 and double bob = (double)(1 + 1) //will not run
However, it is possible to cast from double to int (more to less complicated) using “(int) (expression goes
in here)”, decimals are removed. This is referred to as explicit type casting.
Int bob = (int)(1 + 2.0) //after casting would results in a int (3)
Object:
something that is being created or manipulated by the program
- Characterized by state and behavior
- An object is an idea that corresponds to some real-world object that is being represented by the
program
Object reference:
a variable that represents an object
Object Class:
the superclass of which every class automatically extends
null reference
- An object reference variable that does not currently point to an object
- name = null; / if(name == null)
- Following a null reference causes a NullPointerException to be thrown
this reference
- Allows an object to refer to itself
- Refers to the object thru which the method is being executed (inside a method)
- Call another constructor
- Variable shadowing
- Call object itself (System.out)
Example: For example, you can use this to print the object itself. You can say System.out.println(this) and
it will call the toString(); function, which will print the object.
Example: Third example, let's say you would like to simply create a method called "deposit" that adds to a
bank account's balance. If the bank account has an instance variable called "balance," the method's
statements do not need to be this.balance += amount;, and instead, they can be balance += amount;. The
use of "this" here is unneeded.
Instantiation
- className objectName = new className(); // instantiating objects in the main class
- We say that “objectName” is a reference to the object
- String stringName = new String(“stringLiteral”);// String class
- String stringName = “stringLiteral”; // equivalent to above method for String class
Reference assignment
- For object references, assignment copies the memory location
- bishop2 = bishop1; (now pointing to where bishop1 was pointing to)
- equals is defined for all objects, but unless we redefine it when we write a class, it has the same
semantics as the == operator (only tells whether it’s pointing to the same object, not its value)
- public boolean equals( Fraction f )
{
if( numerator == f.numerator && denominator == f.denominator )
return true;
return false;
}
static modifier
- Objects do not need to exist in order to be used or exist
- ClassName.methodName( parameter )
- Wrapper classes, System.out/in, Math
- Can only have other static variables or local variables that are passed in ( no private int a; )
- public class AClass
{
public static int sum( int x, int y )
{
return x + y;
}
}
- int k = AClass.sum( 3, 4 );
- Mutator methods are often void methods as they change or modify a variable inside the method
body instead of returning a value
- Calling a void method (from a different class): objectName.methodName();
- Ex:
- foo.addToBalance(); // adds 50 to balance each time method is called
- Calling a void method (in the same class): methodName();
- Ex:
- addToBalance();
Overloaded methods:
two or more methods in the same class (or a subclass of that class) that have the same name but different
parameter lists
- Method’s signature: consists of the method’s name and a list of the parameter types
- The return type of a
- method is irrelevant
Scope:
the region in which the variable or method is visible and can be accessed
Local variable:
defined inside a method
- The scope extends from the point where it is declared to the end of the block in which its
declaration occurs
Implicit parameter:
an instance method is always called for a particular object (referred to with the keyword this)
Aliasing:
having two references for the same object
- Changing the object information will change the other’s reference too
- To copy values, there must be a new object declared
- Ex: Date birthday = new Date(d.getMonth(), d.getDay(), d.getYear());
Parameters:
passed by value
- For primitive types, this means that when a method is called, a new memory slot is allocated for
each parameter
- The value of each argument is copied into the newly created memory slot corresponding to each
parameter
- During the execution of the method, the parameters are local to that method
- Any changes made to the parameters will not affect the values of the arguments incall
Literal Strings
- May include “escape” characters
- \\ stands for \
- \n stands for a newline
- String s1 = “C:\\jdk1.4\\docs”;
10
Concatenation
- Concatenation operator: +
- Given two String operands lhs and rhs, lhs + rhs will produces a single String consisting of lhs
followed by rhs
- If either lhs or rhs is an object other than a String, the toString method of the object is
invoked, and lhs and rhs are concatenated as before
- If one of the operands is a String and the other is a primitive type, then the non-String
operand is converted to a String and concatenation occurs as before
- If neither lhs or rhs is a String object, an error occurs
- Example:
Date d1 = new Date(8, 2, 1947); // 8/2/1974
Date d2 = new Date(2, 17, 1948); // 2/17/1948
String s = “My birthday is “ + d2; // s has value: “My birthday is 2/17/1948”
String s2 = d1 + d2; // error: + is not defined for Date objects
String s2 = d1.toString() + d2.toString() // s3 has value: “8/2/19742/17/1948”
Immutability
- Once created, a string cannot be changed; none of its methods can change the string
- Immutable objects are convenient because several references can point to the same object safely
- No danger of changing an object through one reference without the others being aware of
the change
11
Empty Strings
- Has no characters, length = 0;
- String s1 = “”;
- String s2 = new String();
- Not the same as an uninitialized string
- private String errorMsg;
- errorMsg = null;
Constructors
- The constructor's name is always the same as the name of the class. The reason for this is because
it specifies the creation of an object of the class. It has no return type.
- No-args and copy constructors are not used much
- String s1 = new String();
- String s2 = new String(s1);
- Example:
/* Default Constructor Follows */
public BankAccount() {
password = "";
balance = 0.0;
}
BankAccount b = new BankAccount();
12
Example 2:
/* Constructor with Parameters Follows */
Methods — substring
- String s2 = s.substring(i, j); → returns the substring of chars in positions from i to j-1
- String s2 = s.substring(n); → returns the substring from the nth char to the end
- “strawberry”.substring(2, 5); → returns “raw”
- “emptiness”.substring(9); → returns “” (empty string)
Methods — concatenation
- Concat - str.concat(str) - "cares".concat("s") returns "caress"
- String result = s1 + s2; concatenates s1 and s2
- String result = s1.concat(s2); the same as s1 + s2
- result += s3; concatenates s3 to result
- result += num; converts num to String and concatenates it to result
13
14
- String s = String.valueOf(n);
- str[i] = String.valueOf(i); // use in a for loop
- DecimalFormat class can be used for formatting numbers into strings
Example of toString:
Methods — Contains
- String date = “July 5, 2012 1:28:19 PM”;
- String str1 = date.contains(“e”); // false
- String str2 = date.contains(“Ju”); // true
- The contains() method checks whether a string contains a sequence of characters.
- Returns true if the characters exist and false if not.
15
16
Methods — Character
- java.lang.Character: “wrapper” class that represents characters as objects
- Character has several useful static methods that determine the type of a character (letter, digit,
etc.)
- Also has methods that convert a letter to the upper or lower case
- if(Character.isDigit(ch)) … → return true if ch belongs to the corresponding category
- if(Character.isDigit(str.charAt(i))) FOR IF STAT AND CHARAT
- .isLetter…
- .isLetterOrDigit…
- .isUpperCase…
- .isLowerCase…
17
StringBuffer class
- Represents a string of characters as a mutable object
- Constructors:
- StringBuffer() // empty StringBuffer of the default capacity
- StringBuffer(n) // empty StringBuffer of a given capacity
- StringBuffer(str) // converts str into a StringBuffer
- Adds setCharAt, insert, append, and delete methods
- toString method converts this StringBuffer into a String
Review
- What makes the String class unusual?
- Treated like any type of object yet is not a primitive data type
- Can be empty
- Do not have to be created/imported
- How can you include a double quote character into a literal string?
- “”””
- Is “length”.length() allowed syntax? If so, what is the returned value?
- Yes; 6
- Define immutable objects.
- Objects that cannot be changed or modified
- Does immutability of Strings make Java more efficient or less efficient?
- Both; immutability makes Java less buggy, but it is also more wasteful because you have
to make a new string for every new change
- How do you declare an empty string?
- String s1 = “”;
- Why are String constructors not used very often?
- Strings are immutable, so it’s easier to copy a string than copy a reference
- If the value of String city is “Boston”, what is returned by city.charAt(2)? By city.substring(2, 4)?
- s, st
- How come String doesn’t have a setCharAt method?
18
- Strings are immutable, so it would return a new string with the request changed character
instead of altering the original string
- Is s1 += s2 the same as s1 = s1 + s2 for strings?
- No, because it concatenates s2 to s1 instead of forming a new s1 object
- What do the indexOf methods do? Name a few overloaded versions.
- Returns the position of the first occurence of the character c in the string
- s.indexOf(‘e’);
- s.indexOf(‘e’, 4);
- What is more efficient for strings: == and other relational operators or equals and compareTo
methods?
- == only refers to the addresses of the Strings, .equals and compareTo refers to the value
of the Strings
- What does the trim method do?
- Deletes whitespace before and after the string
- What does s.toUpperCase() do to s?
- Capitalize all letters in String s
- What does the toString method return for a String object?
- Returns string representation of the object
- Name a simple way to convert a number into a string.
- toString(int n), valueOf(n)
- Which class has a method for converting a String into an int?
- Java Integer class (parseInt())
- Name a few Character methods that help identify the category to which a given character belongs.
- isDigit, isLetter, isLetterOrDigit, isUpperCase, isLowerCase, isWhiteSpace
- What is the difference between the String and StringBuffer classes?
- You cannot change String classes, but you can change the StringBuffer class
Integer class
- Integer (int value)
- Constructs an Integer object from an int (boxing)
- int compareTo( Integer other )
- Returns 0 if the value of this Integer is equal to the value of other
- Returns a negative value if it is less than the value of other
- Returns a positive value if it is greater than the value of other
- int intValue()
- Returns the value of this Integer as an int (unboxing)
19
Double class
- Double (double value)
- Constructs a Double object from a double (boxing)
- double doubleValue()
- Returns the value of this Double as a double (unboxing)
- int compareTo(Double other)
- Returns 0 if the value of this Double is equal to the value of other, a negative integer if it
is less than the value of other, and a positive integer if it is greater than the value of other
- boolean equals(Object obj)
- Method overrides equals in class Object
- Returns true if and only if this Double has the same double value as obj
Note
- Integer and Double objects are immutable; there are no mutator methods in these classes
- If the parameter object for compareTo fails the is-a test, an error will occur
20
Math.random
- You always want to do this: int num = (int) (Math.random() * 100); // *100 because it will only
give you a number between 0.0 and 1.0;
- Multiplying a number x with Math.random() will result in a random real value y in the range of
0.0 < y < x
- Adding a number x with Math.random() will result in a random real value y in the range of x < y
< 1.0 + x
- In general, to produce a random value in the range lowValue < x < highValue:
double x = (highValue - lowValue) * Math.random() + lowValue; //for doubles
int x = (int)(Math.random() * ((highValue - lowValue) + 1)) + min; //for ints
Example:
boolean user = true;
if ( user == true) {
System.out.println("it's true");
21
} else {
System.out.println("it's false");
}
22
23
-
All of the NOTs(!) become true, giving us (a !=b) && (b>7). We then reverse the != to ==, the && to ||,
and the > to <=. Therefore, we get (a==b) || (b<=7), or option C.
Unit 4: Iteration
Before, we actually talk about For loops, and While loops we must understand what an Iteration is; an “
Iteration is a technique used to sequence through a block of code repeatedly until a specific condition no
longer exists or exists.” So, what that means is that it's pretty much a conditional statement used in java.
There are also “do - while” loops but I don’t think that's on the test. (but if you still wanna learn about it:
https://beginnersbook.com/2015/03/do-while-loop-in-java-with-example/)
24
Syntax:
Example:
Int x = 1;
while( x <= 10) {
System.out.println(“Help!”);
X++;
} // this program will run until x is equal to 10
// So it would run 10 times.
Syntax:
for (initialization; test, update) { // this is the header
Statement; // this is the body
… // it’s where you write the things repeated
Statement;
}
Example:
25
Example Syntax:
26
}
public static void setName(String n )
{
name = n; //Remember, instance variable before the variable given. ALWAYS
}
}
5.2 Constructor
Constructor: creates an object of a class; name is always the same as the class, and has no return type
27
1. Default constructor: has no arguments and provides reasonable initial values for the object
2. Constructor with parameters: sets the instance variables of an object to the values of those
parameters
3. Object variables do not store the objects themselves, only the inputs
- Example:
/* Default Constructor Follows */
public BankAccount() {
password = "";
balance = 0.0;
}
BankAccount b = new BankAccount();
Example 2:
/* Constructor with Parameters Follows */
28
29
30
31
Overloaded methods: two or more methods in the same class (or a subclass of that class) that have the
same name but different parameter lists
- Method’s signature: consists of the method’s name and a list of the parameter types
- Return type of a method is irrelevant
Var1 is: 0
Var2 is: null
Static variable (class variable): contains a value that is shared by all instances of the class
- Static: memory allocation happens only once
- Used to keep track of statistics for objects of the class
- Accumulate a total
- Provide a new identity number for each new object of the class
32
Static final variables (constants): cannot be changed and are often declared public
Static method (class method): a method that performs an operation for the entire class, not its individual
objects
- Static method cannot call on an instance method or variable
- Invoked by using the class name with the dot operator
- Usually a class creates no objects of the class
33
While programs are typically designed to achieve a specific purpose, they may have unintended
consequences.
System reliability is limited. Programmers should make an effort to maximize system reliability.
Legal issues and intellectual property concerns arise when creating programs.
The creation of programs has impacts on society, economies, and culture. These impacts can be beneficial
and/or harmful.
34
Initialization
- All of the below methods creates an array of 25 double values and assigns the reference data to
this array:
1. double [ ] data = new double [ 25 ];
2. double data [ ] = new double [ 25 ];
3. double [ ] data;
data = new double [ 25 ];
- Initializer List
- int [ ] coins = {1, 2, 4, 5, 6};
Length of Array
- length: a final public instance variable that can be accessed when you need the number of
elements in an array
- Note:
1. The array subscripts go from 0 to name.length - 1; therefore, the test on i in the for loop
must be strictly less than names.length
2. length is not a method and therefore is not followed by parentheses. Contrast this with
String objects, where length is a method and must be followed by parentheses.
For example,
35
36
2:
for( int i = 0; i < b.length; i++ )
b[i] += 3;
Unit 7: ArrayList
7.1 Introduction to ArrayList
Array Lists
- An ArrayList provides an alternative way of storing a list of objects and has the following
advantages over an array:
- An ArrayList shrinks and grows as needed in a program, whereas an array has a fixed
length that is set when the array is created
- In an ArrayList list, the last slot is always list.size() - 1, whereas in a partially filled array,
you, the programmer, must keep track of the last slot currently in use
- For an ArrayList, you can do insertion or deletion with just a single statement. Any
shifting of elements is handled automatically. In an array, however, insertion or deletion
requires you to write the code that shifts the elements.
- It is easier to print the elements of an ArrayList than those of an array. For an ArrayList
list and an array arr, the statement
System.out.print( list );
will output the elements of the list, nicely formatted in square brackets, with the elements
separated by commas. Whereas to print the elements of arr, an explicit piece of code that
accesses and prints each element is needed. The statement
System.out.print( arr );
will produce a weird output that includes an @ symbol and the hashcode of the array in
hexadecimal.
- Standard format to create an arrayList: ArrayList<E> array = new ArrayList<E>();
37
38
39
Each method above that has an index parameter ( add, get, remove, and set ) throws an
IndexOutOfBoundsException if the index is out of range. For get, remove, and set, index
is out of range if
For add, however, it is okay to add an element at the end of the list. Therefore index is
out of range if
40
7.5 Searching
h ttps://www.youtube.com/user/AlgoRythmics - Dancing Algorithms! Good visuals
Binary
Pseudocode: Not quite efficient, but for the learning purposes. Only works on SORTED arrays. :) First of
all, we have two “searchers” starting at the ends of the array (max and min, hence the name “binary”). We
find the middle of the array and compare our search value to it. Is the search value greater? Okay, move
the min searcher to mid+1. Is the search value less than? Okay, move the max value to mid-1. Then we
repeat with the new min/max. Find a mid between them and compare search value. You should know
what happens after.. Ask the two questions...do it... alllll the way until we find that the mid matches the
search value. Bingo!
Linear
Pseudocode: Basically, go through each element one by one and compare it to the value
that you are looking for. If the current element and the search value are not equal, move on. If they are,
the search is done and return the index of where you found the match.
Computers store vast amounts of data. One of the strengths of computers is their ability to find things
quickly. This ability is called searching. For the AP CS A exam you will need to know both sequential
search and binary search.
41
- Sequential search typically starts at the first element in an array or list and looks through all the
items one by one until it either finds the desired value and then it returns the index it found the
value at or if it searches the entire array or list without finding the value it returns -1.
- Binary search can only be used on data that has been sorted or stored in order. It checks the
middle of the data to see if that middle value is less than, equal, or greater than the desired value
and then based on the results of that it narrows the search. It cuts the search space in half each
time.
7.6 Sorting
Sorting
- Selection Sort - Selected the smallest item from the current location on to the end of the array and
swap it with the current position. Do this from index 0 to the array length - 2. You don’t have to
process the last element in the array, it will already be sorted when you compare the prior element to
the last element.
- Insertion Sort - Insert the next unsorted element in the already sorted part of the array by moving
larger values to the right. Start at index 1 and loop through the entire array.
- Merge sort - Break the elements into two parts and recursively sort each part. An array of one item is
sorted (base case). Then merge the two sorted arrays into one.
42
Scanner class:
- Import the scanner class:
- import java.util.Scanner;
- Create a Scanner:
- canner input =
S new Scanner(S
ystem.i n); / / Create a Scanner object
ystem.o ut.p rintln(" Enter username");
S
-
- Input types:
43
Reference Sheet
ArrayLists Arrays Strings
Declare ArrayList<String> Al = new String[] Ar = new String[7]; String Str = “Comp Sci”
ArrayList<String>();
44
45