AP CSA Study Guide
Curly brackets alignment is a bit janky, not fully accurate but it shouldnt affect consumibility of notes
Unit 1 – Primitive Types
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Primitive Types
Learning Objectives
Why Programming? Why Java?
Variables and Data Types
a group of characters whose value can be changed as needed
Stores data in RAM (Random Access Memory)
Can’t begin with a digit.
Case-sensitive
Final variable
User-defined constant (uses keyword final)
Can’t change the value of the variable
Example:
Variables and Data Types (continued)
int: refers to an integer
Boolean: a logic which evaluates whether a condition is true or false.
Double: decimals (floating-point numbers)
String: Sequence of letters, numbers, spaces, and symbols, or alphanumeric info.
Floating-point numbers
Stored in two parts (a mantissa and an exponent)
Mantissa: Digits of the number
Expressions and Assignment Statements
Arithmetic expressions
Typically consist of parentheses, function calls, and operators
Arithmetic Operators
+ (addition)
o - (subtraction) o * (multiplication) o / (division)
//returns 2 (NOT 2.5) o % (modulus)
o You can control the type (int or double) of output by casting the operands.
Expressions and Assignment Statements (continued)
o != (not equal to) o > (greater than) o < (less than) o >= (greater than or equal to) o ⇐ (less than or equal to)
! (NOT)
&& (AND)
| | (OR)
Applied to Boolean expressions (for compound Boolean expressions)
True or false values are assigned based on the result of a truth table for these logical operators.
Compound Assignment Operators
– =
=
/=
%=
–
j++ or ++j
j is decremented by 1
Operator Precedence
Highest Precedence
!. ++. –
,/,%
>, <, >=, ⇐
==, !=
&&
| |
Compound Assignment Operators (continued)
Lowest Precedence
Input and Output
double x = Call method which reads a floating-point number
double x = …;
Read user input
Scanner Class – simplifies the console and the input
o System.out.println
System class – displays output to the screen.
print method outputs items without going to a new line while println does print the output on the next line.
Example Practice Questions:
Which of the following data types is not primitive?
Long
Integer
String
Boolean
A value can’t be changed if a variable is declared ________.
final
private
boolean
constant
Answer: A final dataType name = value
Unit 2 – Using Objects
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Using Objects
Objects: Instances of Classes
Implement Objects of a specific data type
Data fields –
Also known as instance variables
Methods
Public
Class declaration which suggests that the class can be used by all client programs
Public methods – any client program can access these methods
Objects: Instances of Classes (continued)
Information hiding in Java – restricting access to data and methods
Private methods and variables – Only accessible by methods from that class
Java does allow public instance variables but we only have private instance variables in the AP Java Subset.
Static
Static variable – class variable
Uses of a static variable
Static final variable (also known as constant)
Methods
Except constructors and static methods
public void deposit (String password, double amount) o public – access specifier
void – return type
withdraw – method name
(Strong password, double amount)- list of parameters
Types of methods:
Instance methods
Constructors
Creates an object or a new instance of the class
Default constructor – No arguments
Constructor with parameters have instance variables set to the values of the parameters.
Object variables store the values and addresses of their respective objects.
Accessors
Access a class object without modifying an object
Returns information about the object
. (dot) operator signals a method of a class
Mutators
Alters the state of an object
Changes at least one of the instance variables of the object
Invoked similar to an accessor in a client program
Methods (continued)
Static Methods
Static methods vs. Instance methods
Static methods use the keyword static for its implementation.
No implied objects in static method (there is in instance methods)
A static method can use a static variable in the code.
Overloaded methods are two or more methods which are in the same class and have the same name but different inputs or parameter lists
Compiler decides which method to call by looking at the method’s signature
Method signature – consists of method’s name, parameter types
Return type is irrelevant for overloaded methods
Scope
Scope of a variable or method means that it’s in an area where the identifier is
visible and can be easily accessed
What does a scope consist of?
Instance variables
Static variables
Methods of a class
From the opening brace to the closing brace of a class.
Methods (continued)
Inside a method
Can be defined in a statement
Scope extends from the beginning to the end of the block it is defined in
Block – code enclosed in {}
The memory of a local variable or method is recycled when a block is exited
Higher precedence over instance variables
Using same names creates ambiguity for programmers and coders (Leads to more errors)
String Objects: Concatenation, Literals, and More
String literals have zero or more characters in them.
Can also include escape sequences
String literals are surrounded by double quotes.
Used on String objects
Allows you to combine two or more String operands
Don’t use (=
for testing or comparing String Objects.
String Methods
Using the equals method
Using the compareTo method
Int compareTo (string otherStringYouAreComparing)
stringOne. compareTo (stringTwo) < 0
stringOne. compareTo (stringTwo) > 0
stringOne. compareTo (stringTwo) == 0
REMEMBER THAT JAVA IS CASE-SENSITIVE!
Wrapper Classes: Integer and Double
This wraps a value of int type in any object
Only contains one instance variable with the type int
Int methods you should know for the exam
Double Class
This wraps a value of double type in any object
double (double value) o double doubleValue()
o int compareTo (Double other)
boolean equals (Object obj) o String toString()
Using the Math Class
o static double abs(double x) o static double pow(double base, double exp) o static double sqrt(double x) o static double random()
Unit 3 – Boolean Expressions
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Boolean Expressions
Boolean Expressions
Inventor of the concept of Boolean logic
He also developed the idea of what computers can use to make decisions – condition statements.
if Statements and Control Flow
o Most basic control flow statement o If it’s false, the computer should skip the code and continue with the rest of the program.
Can modify or break the flow of the execution
To execute certain blocks of code in your program.
Switch statements
Can test a range of values
Can use these statements if the if-else chain is too long.
Looping statements
Branching statements
if-else Statements
If the condition is true, the computer executes the block of code but if the condition is false, the computer executes the else action.
Will always take some action because the condition has to be either true or false (not in the middle).
Optional else statement
else-if Statements
In Java, once a block of code is executed, it doesn’t check for the other else-if conditions
Equivalent Boolean Expressions
not (a and b) → (not a) or (not b)
not (a or b) → (not a) and (not b)
o !(a || b) is equivalent to !a && !b
You can do this with relational operators
<, >, or ==
Comparing Objects
Provide behaviors of the object
Provide operations which manipulate the object
Comparing String Objects
Using the equals method
Using the compareTo method
Int compareTo (string otherStringYouAreComparing)
stringOne. compareTo (stringTwo) < 0
stringOne. compareTo (stringTwo) > 0
stringOne. compareTo (stringTwo) == 0
String Objects – immutable
Don’t use (=
for testing or comparing String Objects.
Unit 4 – Iteration
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Iteration
while Loops and for Loops
for loops repeat for a range of values
while loops repeat when a condition is true/met
for loops have a start value for the loop variables
for loop can be best when you know how many times to repeat the code
while loops can be best when you don’t know how many times to repeat the code
* Example of a while loop
public class Test { public static void main(String[] args)
{
int x = 10;
while (x > 0)
{
System.out.println(x); x = x - 2;
}
}
}
while Loops and for Loops (continued)
public class Test {
public static void main(String[] args) {
for (int x = 3; x > 0; x--)
{
System.out.println(x);
}
}
}
* Body of the loops
A single statement after “while” or “for”
OR
Block of code between the opening and closing curly braces.
Developing Algorithms Using Strings
o String processing
The code processes a string by each character.
o int indexOf(String Str)
String substring (int from, int to)
String substring (int from)
Determine how many substrings meet the criteria
Create new strings with the characters of an existing string reversed.
Nested Iteration
Used when working with two dimensions such as arrays and
ArrayLists.
{
public static void main(String[] args)
{
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 5; col++)
{
System.out.print("*");
}
System.out.println();
}
} }
Informal Code Analysis
Unit 5 – Writing Classes
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Writing Classes
Anatomy of a Class
String variables
Instance Variables
Attributes and behaviors
Hold data for objects
Instance variables
Attributes/behaviors
Fields
Properties
Anatomy of a Class (continued)
private String first;
private String last;
public Name(String theFirst, String theLast)
{
first = theFirst; last = theLast;
}
}
o Data o Constructors o Methods
Constructors
A constructor with parameters needed for initializing any instance variables.
Documentation with Comments
Preconditions
Condition must be true before the code is implemented.
Postconditions
Should be true after a method is run
Describes the output/outcome after the method is run
Shows different ways a user can interact or use the program before its built
Documentation with Comments (continued)
*/ public Snake(int x, int y) { xPos = x; yPos = y; }
Accessor Methods
Return by value
Original value can’t be modified
A way to access the instance variables of the class
toString method
Overridden method
Incorporated in classes to show a description of the object
Called when print statements are passed as objects
Mutator Methods
Writing Methods
Method definition
Method Signature
Method body
Object.method()
To call an object’s method
Reusing code
Maintainability and debugging
Static Variables and Methods
o Can be public or private
Belong to class
Objects share single static variables
Used with class name and dot operator
Static methods
Associated with class
Cannot access or modify any values of the instance variables
Can modify the values of static variables.
Can’t call non-static methods
Scope and Access
Method Level Scope
Local variables
Parameter variables
Block level scope
Unit 6 – Array
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Array
Array Creation and Access
o Elements of type int are initialized to 0 o Elements of type double are initialized to 0.0 o Elements of type boolean are initialized to false o Elements of a reference type are initialized to the reference value null. No objects are automatically created.
Square brackets ([ ]) are utilized to get to and adjust a component in an Array utilizing a list. The indexed value, for instance array[index], can be utilized anywhere a normal variable can be utilized, for instance to get or assign any values or variables.
The valid index values for an array are 0 through one less than the size of the array. Utilizing a record and index value outside of this range will give you an
ArrayIndexOutOfBoundsException.
Traversing Arrays
public class
OffByone {
public static void main(String[] args)
{
int[ ] scores = { 10, 9, 8, 7, 6};
* Make this loop print out all the scores! for (int i = 1; i ⇐ scores.length; i++)
{
System.out.println( scores[i] );
}
} }
Enhanced for Loop for Arrays
Can be used in an array without specifying an index variable.
Developing Algorithms Using Arrays
Unit 7 – Array List
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
ArrayList
Introduction to ArrayList
ArrayList are re-sizable groups that permit adding and expelling things to change their size during run time.
The
ArrayList class is in the java.util Java package. You should import java.util.* to utilize it.
An
ArrayList object contains object references and is variable, which means it can change (by including and expelling things from it).
Java permits the nonexclusive sort
ArrayList<E>, where the conventional kind E determines the sort of the components, such as String or Integer. Without it, the sort will be Object.
ArrayList<E> is favored over
ArrayList since it permits the compiler to discover mistakes that would some way or another be found at run-time.
When
ArrayList<E> is indicated, the kinds of the reference boundaries and return type when utilizing its techniques are type E.
ArrayLists can't hold primitive data types such as int or double, so you should utilize the wrapper classes Integer or Double to place numerical values into an
ArrayList.
ArrayList Methods
int size() - returns number of elements in the list
Traversing ArrayLists
ArrayLists can be traversed through an enhanced for each loop , or while/for loops by specifying an index.
Deleting components during a traversal of an
ArrayList requires utilizing extraordinary techniques to abstain from skipping elements, since removing an element moves all the other elements.
Modifying the size of an
ArrayList while traversing it utilizing the enhanced for each loop will give us a
ConcurrentModificationException being tossed. So, when utilizing enhanced for loop to traverse through an
ArrayList, you can't add or remove any elements.
Developing Algorithms Using ArrayLists
Searching
Sequential/linear search algorithms check every component all together until the value is found or all components in the Array or
ArrayList have been checked.
The binary search algorithm begins at the center of a sorted array or
ArrayList and disposes half of the Array or
ArrayList in every iteration until the value is found or all the elements have been checked.
Sorting
-
Selection Sort
Insertion Sort
Ethical Issues Around Data Collection
o “Contribute to Society and human well-being.” o “Avoid harm to others.” o “Respect the privacy of others.” o “Give proper credit for intellectual property.”
“Access computing and communication resources only when authorized to do so.”
information or click on certain dangerous links.
Privacy settings: Privacy settings and the complexity of your passwords
determines whether you are volunteering your personal information to be out there or keep your information safe.
Sharing passwords: DO NOT share your password (even with your closest friends or partner).
Dummy sites: Clicking on random pop-ups that are attractive might seem like a good idea until your personal information is stolen. Make sure you check for consistent copyright tags on each page if you are asked to navigate to any external links.
Ethical Issues Around Data Collection (continued)
o They help organizations be more effective because of the software that is built especially for businesses. o Many companies end up with unlimited access to a lot of personal information due to this idea of enterprise software. o They still hold the responsibility of keeping this information safe.
A document which outlines the procedures and protects the business’s data in case a disaster occurs.
Every company is required to have some form of a disaster recovery plan.
Backup: Have a backup of your data to make sure that you can restore files and data and be able to return to normal
ASAP.
Mitigation: This is known as the effort to reduce the impact of a disaster by being prepared with backups, checklists, and an emergency plan.
Monitoring: This can help you prevent any potential risks and keep any eye out for anything that might go wrong.
Redundancy: Having redundant backups is very useful because it reduces the downtime for your company and also allows for a faster recovery period.
Response: This is known as the emergency response plan. It outlines how the business will respond and what actions they should prioritize to get it up and running again.
Few Types of backups
Full backup
Incremental Backup
Differential Backup
Mirror Backup
Unit 8 - 2D Array
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
2D Array
2D Arrays
2D Arrays (continued)
Ordering 2D array elements where traversal occurs across each row While “column-major order” traversal occurs down each column. public class
TwoDArrayInitGet { public static void main(String[] args) { String[][] seating = { {“Sarah”, “Maria”},
{“Cameron”, “Ella”}, {“Emma”, “Luke”} }; String name = seatingInfo[0][0]; System.out.println(name + “ is at [0,0]”); } }
Traversing 2D Arrays
Row-major order
Column-major order
Linear searches
The information below is from Runestone Academy and it is specified that this is tested on the AP exam!
2d Array Declaration - To declare an array, specify the type of elements that will be stored in the array, then ([][]) to show that it is a 2d array of that type, then at least one space, and then a name for the array. Examples: int[][] seats; String[][] seatingChart;
2d Array Creation - To create a 2d array, type the name and an equals sign then use the new keyword, followed by a space, then the type, and then [numRows][numCols]. Example: seatingChart = new String[5][4];. This will have 5 rows and 4 columns.
Traversing 2D Arrays (continued)
Example: String[][] seatingInfo = { {“Jamal”, “Maria”}, {“Jake”, “Suzy”}, {“Emma”, “L uke”}}; This will create a 2d array with 3 rows and 2 columns.
Unit 9 – Inheritance
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Inheritance
Creating Superclasses and Subclasses
Common attributes and behaviors of related classes into a single class called
a superclass.
Classes extend a superclass
Keyword Extends
Creating an inheritance relationship
Writing Constructors for Subclasses
{
private String name; public Human(String theName)
{
this.name = theName;
} public String getName()
{ return name;
}
public boolean setName(String newName)
{
if (newName != null)
{ this.name = newName; return true;
* Example (part 2)
} return false;
}
}
public class Employee extends Human
{ private static int nextEmployeeId = 1; private int employeeId; public Employee(String theName)
{ super(theName); employeeId = nextEmployeeId; nextEmployeeId ++;
}
public int getEmployeeId()
{
return employeeId;
}
public static void main(String[] args)
{
Employee emp = new Employee("Ella"); System.out.println(emp.getName()); System.out.println(emp. getEmployeeId ());
}
}
Overriding Methods
Overriding methods
Methods in a subclass have the same method signature.
Overloading methods
Multiple methods have the same name but different parameter types
Different order of the parameters
OR the number of parameters are different
Super Keyword
o super(arguments); o super.method();
Creating References Using Inheritance Hierarchies
Subclass inheriting from a superclass
Formed with an object
Objects at the top of the hierarchy
Polymorphism
Methods in the declared type
Determines the accuracy of a non-static call
Run Time
Methods in the object type
Implemented for a non-static call
Known as polymorphism
Object Superclass
o boolean equals(Object other)
Unit 10 – Recursion
From Simple Studies: https://simplestudies.edublogs.org &
@simplestudiesinc on Instagram
Recursion
Recursion
{ if (n < 5) { return n; } else {
int a = n / 5; int b = n % 5; return mystery(a + b); } } What result do you get for the following callings? mystery (3) answer = 3 mystery (20) answer = 2
Recursion (continued)
Contain at least one base case
Halt the recursion
And contain at least one recursive call
Recursive solutions
Replicated through iterations
Recursion is used to traverse through String, array, and
ArrayList objects.
What is Recursion?
The binary search algorithm begins at the center of an arranged exhibit or
ArrayList and eliminates a portion of the cluster or
ArrayList until the desired value is found or all elements of the
ArrayList have been checked or eliminated from the process.
Merge sort is a recursive sorting algorithm that can be utilized to sort components in an Array or
ArrayList.
call stack - A class characterizes what all objects of that class know (fields) and can do (strategies). You can likewise have information and conduct in the item that speaks to the (class fields and strategies). All objects of a class approach class fields and class techniques, yet these can likewise be gotten to utilizing className.field or className.method().
Common Mistakes
PRACTICE QUESTIONS
PRACTICE QUESTIONS (continued)
Citations
https://runestone.academy/runestone/books/published/apcsareview/Recursion/rEasyMC.html
https://github.com/ajaygandecha/Youtube-Video-
Files/tree/master/AP%20Computer%20Science%20A
Barron’s Test Prep AP Computer Science A 8th Edition