Table of Contents

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

  1. a group of characters whose value can be changed as needed
    1. Stores data in RAM (Random Access Memory)
    • Identifier: A name for a parameter, variable, user-defined method, constant or user-define class.
      1. A sequence of digits, letters, and the underscore.
  1. Can’t begin with a digit.
    1. Case-sensitive
      • Lowercase when naming identifiers for variables and methods.
      • Uppercase letters are used to separate words.

Variables and Data Types (continued)

  1. int: refers to an integer
    • positive, negative whole numbers (including 0)
  1. Boolean: a logic which evaluates whether a condition is true or false.
    1. Double: decimals (floating-point numbers)
      • Uses 8 bytes
  1. Mantissa: Digits of the number

Expressions and Assignment Statements

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)
  1. ! (NOT)
  1. && (AND)
  1. | | (OR)
  1. Applied to Boolean expressions (for compound Boolean expressions)
  1. True or false values are assigned based on the result of a truth table for these logical operators.

Compound Assignment Operators

  1. – =
    • x -= 7 or x = x - 7
  1. =
    • x *= 9 or x = x * 9
  1. /=
    • x /= 10 or x = x / 10
  1. %=
    • x %= 4 or x = x % 4
    • Increment and Decrement Operators o ++
    • i++ or ++i
    • i is incremented by 1
    • j++ or ++j
    • j is decremented by 1
    • Operator Precedence
  1. Highest Precedence
    • !. ++. –
    • ,/,%
    • >, <, >=, ⇐
    • ==, !=
    • &&
    • | |

Compound Assignment Operators (continued)

  1. Lowest Precedence
    • Simple Assignment
    • Compound Assignment Operators

Input and Output

  1. double x = Call method which reads a floating-point number
  1. double x = …;
o System.out.println
  1. System class – displays output to the screen.
  1. print method outputs items without going to a new line while println does print the output on the next line.

Example Practice Questions:

  1. Which of the following data types is not primitive?
    1. Long
    2. Integer
    3. String
    4. Boolean
  1. A value can’t be changed if a variable is declared ________.
    1. final
    2. private
    3. boolean
    4. 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

  1. Implement Objects of a specific data type
  1. Public methods – any client program can access these methods

Objects: Instances of Classes (continued)

  1. Information hiding in Java – restricting access to data and methods
  1. Private methods and variables – Only accessible by methods from that class
    1. Java does allow public instance variables but we only have private instance variables in the AP Java Subset.
  1. Uses of a static variable
    • Accumulation of a total
    • Providing a new identity for each instance or object in a class
    • Keeping track of data of the objects in a class
  1. Static final variable (also known as constant)
    • Cannot be changed
    • Often declared as public
    • Keyword static indicates that the single value applies to the entire class and not just a new instance for an object in the class.

Methods

  1. Except constructors and static methods
  1. public void deposit (String password, double amount) o public – access specifier
  1. void – return type
  1. withdraw – method name
    1. (Strong password, double amount)- list of parameters
  1. Constructors
    • Creates an object or a new instance of the class
    • Default constructor – No arguments
      • Provides initial values for each new object
    • Constructor with parameters have instance variables set to the values of the parameters.
    • Object variables store the values and addresses of their respective objects.
  1. Accessors
    • Access a class object without modifying an object
    • Returns information about the object
    • . (dot) operator signals a method of a class
  1. 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)

  1. Static Methods
    • Performs an operation for the whole class
    • Not individual objects
    • Sometimes known as a class method
  1. 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.
  1. Overloaded methods are two or more methods which are in the same class and have the same name but different inputs or parameter lists
  1. Compiler decides which method to call by looking at the method’s signature
  1. Method signature – consists of method’s name, parameter types
    1. Return type is irrelevant for overloaded methods
      • Two methods can have similar method signatures but not different return types (compiler will give you an error)
visible and can be easily accessed
  1. What does a scope consist of?
    • Instance variables
    • Static variables
    • Methods of a class
  1. From the opening brace to the closing brace of a class.

Methods (continued)

  1. Inside a method
  1. Can be defined in a statement
  1. Scope extends from the beginning to the end of the block it is defined in
  1. Block – code enclosed in {}
  1. The memory of a local variable or method is recycled when a block is exited
  1. Higher precedence over instance variables
  1. Using same names creates ambiguity for programmers and coders (Leads to more errors)

String Objects: Concatenation, Literals, and More

  1. String literals have zero or more characters in them.
  1. Can also include escape sequences
    1. String literals are surrounded by double quotes.
      • Quotes are not part of the string object.
  1. Used on String objects
    1. Allows you to combine two or more String operands

String Methods

  1. Using the equals method
  1. Using the compareTo method
    • Int compareTo (string otherStringYouAreComparing)
    • stringOne. compareTo (stringTwo) < 0
      • stringOne precedes stringTwo in a dictionary
    • stringOne. compareTo (stringTwo) > 0
      • stringTwo precedes stringOne in a dictionary
    • stringOne. compareTo (stringTwo) == 0
      • both Strings are identical
  1. REMEMBER THAT JAVA IS CASE-SENSITIVE!

Wrapper Classes: Integer and Double

  1. This wraps a value of int type in any object
    1. Only contains one instance variable with the type int
    2. Int methods you should know for the exam
      • Integer (int value)
        • To construct an integer
      • int compareTo (Integer other)
      • int intValue()
      • boolean equals (Object obj)
        • Overrides equals in class Object.
  1. double (double value) o double doubleValue()
o int compareTo (Double other)
  1. 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

  1. Inventor of the concept of Boolean logic
  1. 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.
  1. Can modify or break the flow of the execution
    • Implementing decision making
    • Looping
    • Branching program
    1. To execute certain blocks of code in your program.
  1. Can use these statements if the if-else chain is too long.
  1. Looping statements
    • for
    • while
    • do-while
  1. Branching statements
    • break
    • return
    • continue

if-else Statements

  1. If the condition is true, the computer executes the block of code but if the condition is false, the computer executes the else action.
  1. Will always take some action because the condition has to be either true or false (not in the middle).
  1. Optional else statement
    • Alternate path if the boolean value might be false

else-if Statements

  1. In Java, once a block of code is executed, it doesn’t check for the other else-if conditions
    • Breaks the loop

Equivalent Boolean Expressions

  1. not (a and b) → (not a) or (not b)
  1. not (a or b) → (not a) and (not b)
o !(a || b) is equivalent to !a && !b
  1. You can do this with relational operators
    1. <, >, or ==

Comparing Objects

  1. Provide behaviors of the object
    1. Provide operations which manipulate the object
  1. Using the compareTo method
    • Int compareTo (string otherStringYouAreComparing)
    • stringOne. compareTo (stringTwo) < 0
      • stringOne precedes stringTwo in a dictionary
    • stringOne. compareTo (stringTwo) > 0
      • stringTwo precedes stringOne in a dictionary
    • stringOne. compareTo (stringTwo) == 0
      • both Strings are identical
  1. String Objects – immutable

Unit 4 – Iteration

From Simple Studies: https://simplestudies.edublogs.org &

@simplestudiesinc on Instagram

Iteration

while Loops and for Loops

  1. for loops repeat for a range of values
  1. while loops repeat when a condition is true/met
  1. for loops have a start value for the loop variables
  1. for loop can be best when you know how many times to repeat the code
  1. 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

  1. A single statement after “while” or “for”
OR
  1. Block of code between the opening and closing curly braces.

Developing Algorithms Using Strings

o String processing
  1. The code processes a string by each character.
o int indexOf(String Str)
  1. String substring (int from, int to)
  1. String substring (int from)
  1. Determine how many substrings meet the criteria
  1. Create new strings with the characters of an existing string reversed.

Nested Iteration

public class NestedLoops

{ 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

  1. String variables
  1. Fields
  1. 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

  1. A constructor with parameters needed for initializing any instance variables.

Documentation with Comments

  1. 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

  1. Incorporated in classes to show a description of the object
  1. Called when print statements are passed as objects

Mutator Methods

Writing Methods

  1. Method definition
  1. Method Signature
    1. Method body
  1. Reusing code
  1. Maintainability and debugging

Static Variables and Methods

o Can be public or private
  1. Belong to class
  1. Objects share single static variables
    1. Used with class name and dot operator
  1. Cannot access or modify any values of the instance variables
  1. Can modify the values of static variables.
  1. Can’t call non-static methods

Scope and Access

  1. Method Level Scope
    • Local variables
    • Parameter variables
    1. Block level scope
      • Loop variables

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.

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

  1. 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 Methods

int size() - returns number of elements in the list

Traversing ArrayLists

Developing Algorithms Using ArrayLists

Searching

Sorting

  1. Used to sort elements in an ArrayList
  1. Selection Sort
  1. 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.”
  1. “Access computing and communication resources only when authorized to do so.”
information or click on certain dangerous links.
  1. 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.
  1. Sharing passwords: DO NOT share your password (even with your closest friends or partner).
  1. 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.
  1. A document which outlines the procedures and protects the business’s data in case a disaster occurs.
    1. Every company is required to have some form of a disaster recovery plan.
  1. 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.
  1. Mitigation: This is known as the effort to reduce the impact of a disaster by being prepared with backups, checklists, and an emergency plan.
  1. Monitoring: This can help you prevent any potential risks and keep any eye out for anything that might go wrong.
  1. Redundancy: Having redundant backups is very useful because it reduces the downtime for your company and also allows for a faster recovery period.
    1. 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.
  1. Incremental Backup
  1. Differential Backup
  1. 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

  1. Row-major order
    1. Column-major order
  1. Linear searches

The information below is from Runestone Academy and it is specified that this is tested on the AP exam!

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

  1. Common attributes and behaviors of related classes into a single class called
a superclass.
  1. Classes extend a superclass
    • Known as subclasses

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

  1. Different order of the parameters
  1. OR the number of parameters are different

Super Keyword

o super(arguments); o super.method();

Creating References Using Inheritance Hierarchies

  1. Subclass inheriting from a superclass
  1. Formed with an object
  1. Objects at the top of the hierarchy

Polymorphism

  1. Methods in the declared type
    1. Determines the accuracy of a non-static call
  1. Implemented for a non-static call
  1. 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)

  1. Contain at least one base case
  1. Halt the recursion
    1. And contain at least one recursive call

What is Recursion?

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