AP Computer Science A Ultimate Guide - 1
AP Computer Science A Ultimate Guide - 1
Primitive Types
The Basics
Commenting, or using comments is your best friend. It’s a very effective tool, and it’s a good idea to get
into the habit of commenting.
It allows programmers to make “notes” in the program so they can reference them later.
Other people viewing your code won’t have trouble interpreting it.
Types of commenting:
In-line/short comments- They appear after or near a statement and are followed by 2 forward
slashes.
Ex:
Long comments- They go beyond more than one line of code that is surrounded by special characters;
they begin with (/) and end off with (/).
Ex:
/* this is a
long comment*/
Identifiers:
Identifiers are names that are given to show data that are stored in the memory of a computer when a
program is being executed in a computer.
**Java is special because it lets the program name the identifier based on its role.
The guidelines below are guidelines to make it easier on us when coding, and its rules that Collegeboard
expects us to follow.
An identifier needs to have a combination of letters, numbers, and underscores(_). However, they
must begin with a letter, and can’t have other characters listed.
An identifier should be named logically, and it should correspond to the data that it is holding.
An identifier should begin with a lowercase letter, and if there are several words used to name the
identifier, then the words after the first should be capitalized.
White space- It doesn’t affect the functionality of the program. It just makes the code easily readable,
because it lets the programmer space out code to separate statements or tasks.
An interpreter is used to change this code into binary(zeros and ones) which is what the computer
understands.
If any sort of errors are found, then the code stops compiling, and an error message appears.
This would be a compile-time error. The computer is unable to compile or understand what the code is
trying to do, which is why it’s unable to execute properly.
Logical error- This is based on the logic of the code. The way that the code is structured, is incorrect.
Run-time error- A compiler doesn’t catch this error. It just causes an error with the execution of the
program.
Using System.out.print;
Using System.out.println;
The print() returns the cursor to the same line after it’s done executing. The println() statement
moves the cursor to the next line.
There are different ways you would print out specific types of outputs.
Ex:
If you want to put a line break in a piece of code just use \n.
Ex:
This specifically tells the compiler that the identifier is side1, and the value that’s being assigned
to it is 2. The data has the integer type.
Note: The equal sign, is an assignment operator, and is very important to have!!
Note: The semicolon’s that we have at the end of each statement mean that the specific statement is
completed.
Ex:
int myFavoriteNumber = 22;
myFavoriteNumber = 78;
System.out.print(“My favorite number is “ + myFavoriteNumber);
The quotation is used so that it specifies what sentence to print out, and what variable value to
print out.
Use concatenation, when you want to combine variables of 2 different types. - The plus sign is
used for this, just like in the example above.
Integer(int)- It represents any number that is an integer. So all positive and negative numbers and
zero. Integers can’t store decimals!!
Double(double)- A number that can be positive, negative, or zero, and it can be a fraction or decimal.
**Boolean(**boolean)- A value that is either true or false. True = 1, False = 0 in machine code.
Arithmetic Operators:
Note: The different operators that are used in Java are the +. - , ,/, and %.
Ex:
Ex:
Ex:
Ex:
side3/side2 = quotientSide;
The percent sign, (%), is called a modulus operator. It does the division of the numbers, and it
returns the remainder.
Ex:
sumOfSides % differenceOfSides;
Just like in normal math, Java also follows an order in which it conducts its operations.
Java performs multiplication and division operators, as well as modulus from left to right, then it does
addition and subtraction in the same order.
If you want to change the order that the operation occurs, just use parentheses to separate the expression
out.
Java likes to do something special with some of its integers. Say that you are dividing 3/2 in reality the
answer is actually 1.5, but Java truncates the 0.5 off. It will display the answer as 1, because it was
described as in integer type, not a double.
Casting- A process in which data is forced to look like another type of data to the compiler.
Both of the examples are the proper way to do casting so that it produces the desired result.
Note: In the order of operations in Java, casting will be done first because it has higher precedence.
==Other operators:==
Increment operator(++)- This increases the value of a number by one. It’s just a shorthand of the
addition operator that can sometimes be used.
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a/b
a %= b a = a % b
Math Class
This store's common numbers used in mathematical calculations and methods to have mathematical
functions.
Note: Static methods, belong to a class, but it doesn’t belong to any instances of that specific class. This
type of method can be called without the class's instance or object.*
Ex: Say you want to calculate the amount of candy each person gets amongst your group of
5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on
using your amazing IDE to help you out. What line of code would best fit your needs?
a. Math.abs(14/5);
b.Math.pow(14,5);
Answer: C would be the only option that fits your needs because you don’t want an absolute value for your number of
chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the
chocolate amount. So, this would be your answer.
String Class
A string is also an object data type, which means it has a class with many methods that describe the
behavior of an object.
Ex: Consider the following code segment, What will be the value of n?
String t = s.substring(5);
int n = t.indexOf(“the”);
Answer: The value of n will be 3. The question is asking for the value of n, which is the indexOf “the” in String t, which
is essentially just a substring of string s. Determine t first, which is the substring that begins at the index 5 of s. Start
at 0 and count the spaces as different characters. Index 5 is the letter i, at the beginning of the word is. Since string t
is a substring of s, the sentence for this substring would be “is the beginning”. the index of “the” is 3 because it
begins at index 3.
There are a lot more methods that are in the String class. However, these are just the main ones.
Remember that the data in the String class is just an array of characters. This means that String’s
have similar functions to arrays.
IndexOutOfBoundsException’s occur when the index that you use in any of the methods above goes
beyond the index of the String.
The String class is an immutable class. This means that if you would like to change the values or content
of a String object the new contents need to be rearranged to help find the variable.
Note: When using methods found in any class, you should remember that parameters that are used to call
the method need to match the data types of the arguments that are found in that specific method.
Make sure that parameters match the correct data types so there are no issues with the execution of the
code.
Classes have instance fields or data that belong to objects and methods that are used to help change the
data.
Math Class
This store's common numbers used in mathematical calculations and methods to have mathematical
functions.
Note: Static methods, belong to a class, but it doesn’t belong to any instances of that specific class. This
type of method can be called without the class's instance or object.*
Ex: Say you want to calculate the amount of candy each person gets amongst your group of
5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on
using your amazing IDE to help you out. What line of code would best fit your needs?
a. Math.abs(14/5);
b.Math.pow(14,5);
Answer: C would be the only option that fits your needs because you don’t want an absolute value for your number of
chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the
chocolate amount. So, this would be your answer.
String Class
A string is also an object data type, which means it has a class with many methods that describe the
behavior of an object.
Ex: Consider the following code segment, What will be the value of n?
int n = t.indexOf(“the”);
Answer: The value of n will be 3. The question is asking for the value of n, which is the indexOf “the” in String t, which
is essentially just a substring of string s. Determine t first, which is the substring that begins at the index 5 of s. Start
at 0 and count the spaces as different characters. Index 5 is the letter i, at the beginning of the word is. Since string t
is a substring of s, the sentence for this substring would be “is the beginning”. the index of “the” is 3 because it
begins at index 3.
There are a lot more methods that are in the String class. However, these are just the main ones.
Remember that the data in the String class is just an array of characters. This means that String’s
have similar functions to arrays.
IndexOutOfBoundsException’s occur when the index that you use in any of the methods above goes
beyond the index of the String.
The String class is an immutable class. This means that if you would like to change the values or content
of a String object the new contents need to be rearranged to help find the variable.
Note: When using methods found in any class, you should remember that parameters that are used to call
the method need to match the data types of the arguments that are found in that specific method.
Make sure that parameters match the correct data types so there are no issues with the execution of the
code.
For example, your parents tell you, you can only watch a movie if you finish cleaning your room.
Cleaning your room is the condition for you to be able to watch the movie.
The else statement in the example below is used for what results to produce when the if condition isn’t
being satisfied.
Ex:
else
Note: The boolean operator( ==), isn’t the same as the assignment operator(=).
A boolean operator asks a question, while an assignment operator executes a command. The boolean
operator in this example determines if num1 is equal to num2.
The assignment statement doesn’t produce other results.
Boolean Expressions
Values that can be compared using boolean statements:
== (equal)
!= (not equal)
==The boolean statement produces a truth value based on the comparison that it conducts.==
Sometimes, however, we might want to create a more complicated condition. This is referred to as a
compound condition. They include at least one boolean operator.
Common Compound Conditions:
|| - logical or
! - logical not
== - is equal to
!= - is not equal to
Ex: Consider the following boolean expression, (X && !Y) || (!X && Y). Which of the following
conditions will always cause the expression to evaluate to true.
Answer: || indicate or for both of the expressions. Note that for or, only 1 of the expressions
has to be true. Both X and Y have to be true in their conditions for the expression within the
brackets to be true. This rules out just the value of just one variable changing because both
are impacted. The values of X and Y can’t match other. This means that X and Y have to
have the opposite truth values.
Answer: Let’s start off with an expression on the right It will simplify to !p && !q. It doesn’t always
evaluate to true or false, because we don’t know the values of p and q, and it’s contingent on
this. The correct answer is that the expression evaluates to false whenever p and q have opposite
values.
The way that if statements work and function applies to all control statements! Make sure you really
understand how it works!
DeMorgan’s Laws are used to help simplify Boolean expressions.
T T T T F F F F
T F F T F T T T
F T F T T F T T
F F F F T T T T
Iteration
Intro to Iteration
When writing statements that might repeatedly appear in code, you can do 2 things.
You can copy and paste the statement multiple times, and spend hours writing code.
A more efficient way would be to use a conditional statement that is referred to as a loop.
Note: On the AP Exam you will be expected to know what while and for loops are.
While Loop
This loop cycles through again and again, while the condition is considered true.
Ex: Say that you have a paintbrush that is soaked in paint, and hopefully you don’t put away the
paintbrush until it is clean. It’s entirely based on the cleanliness of the paintbrush. You will only
put the brush away if it’s true that it is clean.
If the condition is false then the loop will continue to run, until the condition returns true.
However, if the condition is true then it will execute the statement, and it will exit the loop, and if there is
another condition present then that will start running instead.
However, sometimes loops aren’t well written, because sometimes there might not be any sort of
statements that go through the loop to help change the value of the expression to be true.
This would be considered an infinite loop, which, as its name suggests, means that the loop goes on
forever.
It has the similar feeling of TikTok freezing on you when you're on your daily Tiktok spiral.
Note: On the AP Exam, you need to be able to trace code in multiple-choice questions and detect infinite
loops. In the free-response questions, you need to write code that is free of infinite loops.
All loops are dependent on the conditions that are found within them.
If there are multiple conditions found in the loop when can use boolean operators to simplify it. (View
Chapter 5 for a review of boolean operators)
Ex: The paintbrush needs to be cleaned and dried for it to be put away, and if it isn’t then don’t
put the paintbrush away.
In this case, you would end up using the && (and) boolean operator, because while the paintbrush is both
wet and dirty, then only will the paintbrushes be put away.
So if the paintbrush is dirty and wet then don’t put away the paintbrush, otherwise, put away the paintbrush.
Since this loop needs more components, it can help to avoid an infinite loop in some situations.
The initializer will start first and it will start the loop off.
The incrementer will increment the number, and in turn will change it.
The process above starting from step 2 will continue to repeat until the value turns to false.
Ex:
//Explanation: The loop above will show every number and the output on the screen on
separate lines.
Ex:
System.out.println(num);
System.out.println(“Done”);
//Explanation: The example above shows that num starts at the value of 1, and as long
as the number is less than or equal to 3 the for loop will continue to execute. When
the for loop executes it prints the value of num. Each time you go through the loop,
the value of num increases by 1. Once the value of num hits 4, it will exit the for
loop, and print done instead.
Note: On the AP Exam some of the multiple choice questions will show you multiple loop structures and
formats, and ask you to pick which ones run the most efficiently, and which one produces the right output.
The free-response questions will ask you to write a loop.
Note: Make sure to use your best judgment when writing your code for loops, because one loop may run
more efficiently than others, and run on less code. Which means less work for us :)
While loops perform the blocked statement, or statements once, and then it will evaluate the
condition to determine if the loop should continue executing.
For loops evaluate the condition first, and then it performs the blocked statements if the initial
condition is determined to be true.
Writing Classes
Intro to Classes
Classes help out a lot! They will help to make your code a lot less complex to read and understand, and
keeps it organized! It’s a key tool for a programmer to write code efficiently.
Class- When a group of statements, such as control structures, are all put together to be referred to
this.
Note: We all write amazing code, but sometimes the compiler just doesn’t understand, and can’t compile it
into machine code. Make sure to review your code carefully!!
The name of your class should refer to the purpose and function of the class, similar to how you name your
variables.
Note: Remember your indentations!! It needs to be correctly indented for the code to be considered a part
of the class.
In classes, variable declarations are found at the top of the code right after the header.
The .java extension lets the compiler recognize the file as containing java code. If the code compiles and
there are no errors that occur there are other files created in the same class which contains all the machine
language for the computer to execute it.
The .java file is called the source code for a program because it defines the program’s actions and functions.
Methods
Method- A group of code that performs a specific task.
To make your code more readable in a class, try to write out different methods to keep it more organized.
Say you have a list of tasks that you want to complete over the weekend your class in pseudocode would
look something like this:
shower method;
This makes the class more structured and a lot cleaner to read. A class that is created to control a larger
program is called a driver class.
Since it drives the program through its structure to help execute the smaller commands.
Object class-This class houses the “guts” of the methods that the driver class calls.
The object class defines all of the aspects of an object, and it represents what the object has and what the
object does.
The object class in this section shouldn’t be confused with the Object class in Java(that’s considered to be
the parent class of all classes)!
Every class in Java is a descendent of the object class in the Java language.
The programmer needs to write attributes in a class, instance variables, or fields in order for the code to
function correctly.
An object class defines what an object has, and what it does.
The return type, specifies the type of data that will be returned from the methods after its
commands are executed.
Parameters- (these are optional) They are data that the method needs to function properly.
Let’s go back to our breakfast example for this for what a class would look like: public void routine()
To make it more specific we just need to include parameters: public void routine(int minutes)
Remember: A method can have any number of parameters, it is up to the programmer, and how they design
their program.
The purpose of a method is to perform some sort of task with regards to the object.
Sometimes we end up writing multiple methods that perform the same task, but require different
information, or parameters to to something. This is considered overloading.
*/
Postcondition- A condition that must always be true just after the execution of a section of code, or after
an operation in a formal specification.
Note: On the AP Exam, postcondition is also written as a comment before or within the method. The
method designer is responsible for making sure that these conditions are being met.
Ex(Postcondition):
<code>
//postcondition- returns 100, if sum if greater than 100, or the value of the sum
Return sum;
else
Return 100;
Note: A method can accept any number of parameters, but may return only one data value or object.
Tip: Plan out how you are trying to construct your classes based on your needs. It makes it a lot easier to
write the code in the most efficient way possible!
Note: The AP Exam tests the planning of a class by giving a lengthy requirements list that comes along with
the other classes that interact in either their multiple choice questions, or on the FRQ’s.
Composition
In order for the classes to come together and have the program function properly, they need to work
together properly.
Remember: the driver and object classes must be in the same folder on the computer.
Note: The driver depends on the object class in order for the code to compile. The object class depends on
the driver to make it do anything.
Every time we instantiate an object, we need to assign it an object reference variable, or in other words, a
variable name.
Each item has to have its own separate object class when its instance data and methods are different than
that of the other types of data.
The programmer has to take on the responsibility of deciding which objects to instantiate and to which
types and when to use them, and how they are used based on the needs of the class.
Note: The FRQs on the AP Exam will give you content behind the functions of the classes and methods that
you need to write.
this Keyword
It might be necessary for the calling object to refer to itself.
When an object calls a method, a reference is assigned to the calling object. The name of this reference is
this.
this is a keyword used to reference the current calling object and may be used as an object variable.
Static Modifier
A static variable is an attribute that is shared among all instances of a class.
When the value of this variable is changed, the alteration is reflected by all of the objects instantiated
through that specific class.
Think of it like a high-score list on a video game. There is a list of high scores, and the old ones get thrown
out as a new high score emerges.
A non-constructor method that is designed to access or modify a static variable is a static method.
Arrays
Arrays Intro
Arrays- A data structure that makes it easier to handle similar types of data.
Every separate piece of data is referred to as an element, and an index is used to identify the specific
location of this element.
Arrays can be used to make the run-time of code a lot more efficient.
If you already know the data types being stored and the data values, you can instantiate or set up the array
using an initializer list.
Note: Square brackets are used to show that an array is present. While curly brackets indicate an initializer
list, just like the examples above.
As mentioned before each data point will be stored with its unique index.
You can also reassign a value at an index in case you make a mistake entering the numbers.
testGrades[0] = 98;
You can also use arrays to perform integer operations, and display the value.
You can also traverse through the array and change all of the values.
Ex: Your teacher decides to deflate your grades so you have to subtract 2 points from each grade
testGrades[index]-=2;
ArrayindexOutOfBoundsException occurs when the indexes go out of bonds from what the array is actually
set to.
Note: The AP Exam will require you to create, traverse and modify arrays. This is often what the free
response questions are about!!!
Remember to make sure that you assign the correct values for each element found in the array. Otherwise,
you may get a result that you weren’t expecting.
double average;
total += testGrades[index];
double average;
In enhanced-for-loop specifically, a declared array or an ArrayList needs to be referenced after the colon.
The loop then iterates for each element found in the list all the way from index 0 to the last index(length-1).
Note on enhanced for loops: The enhanced for loop provides a variable that will hold each element of an
array. it doesn’t provide the index of an element. You will need to include code to keep track of indexes if
it’s necessary for your code.
Instead, the element located at the current index is stored as the variable declared before the colon.
Overall, the enhanced for loop stores each element in increasing order by the index of the array testGrades
as grade. It then adds grade to the total.
The reason why enhanced for loops are used is because the risk of getting an
ArrayIndexOufOfBoundsException when it traverses the array is less, and it shortens the notation of
elements.
Note: FRQs on the AP Exam test your ability to write code that doesn’t go out of bounds. The AP exam will
require you to create, traverse and modify your arrays.
It’s important to pay attention to the data that you are including in your arrays. Any unassigned value will
just default to 0.
Since each element is an object in an array, the default value for the object will be null. Any operations
performed on null will result in a NullPointerException because null isn’t a valid object!
Arrays are useful to organize and manipulate objects. Just make sure that the array is full of objects so that
it produces the desired results.
Searches
In many cases when you have data stored in an array you may want to search the array for specific values.
It makes it easier to pinpoint values in some cases instead of just using loops.
Sequential searches- These search through the data one by one in order, and take a long time to execute.
Binary searches- These search through the data for the desirable value by dividing it into half each time
until the desired value is found.
Note: On the AP Exam you will be asked to recognize these search algorithms and understand how they
function.
Sorts
Sorting Algorithms- They take data in an array, and rearrange it into a particular order. They are very
powerful because they can accomplish tasks faster, and can make your programs even more efficient.
Selection sort: This sort searches and swaps. Once it finds the lowest value, it will swap its position in the
array with the data at index 0. The first element is now sorted. The process repeated for index 1. The rest of
the array will be searched for the lowest value and is swapped with the data that is found at index 1.
Insertion sort: It compares the first 2 elements, and depending on the outcome of this it inserts the second
value in front of the first value into index 0, which moves the first value to index 1. The first 2 elements are
sorted. Then the third element is checked and this process continues until it’s entirely sorted.
Merge Sort: This type of sort uses recursion. An array is split into 2 pieces. The piece is sorted. The 2
sorted pieces are merged together into one sorted list. Then in order to sort each of the 2 pieces, the same
method is used again until it is fully sorted.
ArrayLists
ArrayLists & Lists
A huge limitation of arrays is that it has a fixed length, and can only store, one specific type of data.
Ex: You have a group of action figures, an array would require that all the action figures are of the
same type. So they would all need to have the same features, ex: flying or protective body armor.
However, the number of action figures is represented using an array set to a fixed number. Extra
spaces will simply be ignored, and once you reach one it will result in a NullPointerException.
An ArrayList object is dynamically sized, it can become smaller or larger as elements are added or
removed.
It’s best to choose between an Array and ArrayList based on your needs and the functionality of the array.
ArrayLists are very adaptable, so if you need to make an ArrayList set to a specific type, you set it up as
typed ArrayList.
The way you access data within an ArrayList is different from that of Arrays.
For example, say you want to return the second object, an Apple Object, from the ArrayList and
store it in a variable.
Arraylists are unique because only objects can be strained in them. The primitive data types of int, and
double can’t be stored in ArrayLists.
Instead, you have to use the Integer or Double wrapper classes. Integer and Double objects can be created
with integers and doubles, as parameters.
Ex:
To call these values from the example above you can use the intValue(), and doubleValue() methods.
Ex:
int a = n.intValue();
int y = x.doubleValue();
Other variables that the AP Computer Science Java Subset includes are the static variables of MINVALUE,
and MAXVALUE found in the Integer class.
These static variables store the minimum and maximum values of an integer.
Ex: Consider the following code segment. What is printed as a result of executing the code
segment?
list.add(“A”);
list.add(“B”);
list.add(0,”C”);
list.add(“D”);
list.set(2,”E”);
list.remove(1);
System.out.println(list);
Answer: It should print out “C E D”. This is because our list at first will be A B. Since we ask to add C to the index of 0
the array will look like this- C A B. Then D gets added to become C A B D. The B gets replaced with E to become C A E
D. Then we remove A, because it’s at index 1. It becomes C E D.
Array ArrayList
Arrays have a fixed length. ArrayLists can resize when new elements are added to it.
You don’t need to have an import statement to use an You have to have an important statement,
array. The only case to use an import statement in an java.util.ArrayList, or the full name of the package when
array would be when the array has specific elements you use the ArrayList.
that require import statements.
Elements can be accessed with index notation. Ex: Different methods are used to access the ArrayList. Ex:
LibraryArray[3]; myList.get(2), myList.add(“Bob”)
Arrays can contain primitive data types(int, float, ArrayLists can only be used to hold object references.
double, boolean, and char), and/or object data types.
They can only hold one specific type of element. Ex: If Has the ability to hold a collection of objects.**However,
the array is said to hold only integers, then it stores this isn’t recommended** Ex: ArrayList list = new
only integers, not other types such as Strings. ArrayList();list.add(new
String(“Hello”));*list.add(new Integer(5));
2D Array
2D Arrays stands for 2-Dimensional Arrays.
So you go to a vending machine and you see the different types of snacks, you know which type you want,
and when you put in your money you hope for the snack to drop out.
The snack machine can be thought of as a set of rows across in the machine with different types of snacks
like chips, and granola bars.
The vertical columns will contain each separate type of snack, so column 1 will just be all chips, and column
2 will just be all granola bars.
The indexes for each item are assigned individually for each row and column’s location.
For example, say you want to get the granola bar in row 3, and it’s in the second column you code would
look like this: vendingMachine{2][1]
The methods that are used in arrays are quite similar to those in 2D arrays, because a 2D array, is just an
array, except more sophisticated.
Important lines of code to remember to figure out the number of rows and columns:
This would tell you the number of slots that are across the machine.
Ex:
//Consider the following code segment, and what it will print out as a result
int [][] numbers = {{1,2,3,4},{5,6,7,8));
for(int[] nums: numbers)
for(int n: nums)
System.out.print(n + " ");
System.out.print("\n");
Answer: It will print 1, 2, 3, 4, 5, 6, 7, 8. This is an enhanced for loop. The first loop uses the idea that a 2D
array is an array of arrays. It goes one row at a time and stores it in nums. The inner loop takes one element
at a time from the row and stores it in n. There are no line breaks, so the array is printed one element after
the other.
Ex:
Answer: The variable identified as arr has been created, which eliminates A, B, and E. The indices of arrays
start at 0, and the range is always one less than the number of rows or columns, and the declaration needs
to use the exact number of rows and columns that are desired in the specific array. Which makes the right
answer to be C.
Inheritance
Inheritance Hierarchies and Design
Inheritance- A way to create a relationship amongst classes.
Inheritance Hierarchy- A way to determine how information travels amongst the classes. Ex: The
subclasses inherit characteristics of the parent class.
The parent class is referred to as the superclass, and the classes that inherit from it are referred to as
subclasses of the superclass.
The parent class is the most general form of the objects that will be instantiated in the program.
All the other classes in the program will lie lower in the hierarchy, but they will be more specific compared to
the parent class.
Let’s think of inheritance using an example, it’s the easiest way to explain this concept.
Ex: Say you want to buy something, and you decide to buy a snack. Then you wonder which type
of snack should I get. You narrow it down to potato chips and cookies. However, there are 2 types
of potato chips(Classic, and BBQ), and 2 types of Cookies(Chocolate Chip, and Macadamia Nut.)
In the example above each of the different snack items is divided up into their own specific categories, and
is like a hierarchy because one thing follows the other.
<<Note: On the AP Exam there is at least 1 free-response question and many multiple-choice questions that
focus on the design and implementation of inheritance relationships.<<
{{Important!!- Classes inherit variables and methods from their superclasses!{{
In some instances, a class may not have more than one direct superclass.
Overridden- When a new version of the code takes over from the old version.
Polymorphism
Polymorphism- When many classes are related to each other by inheritance. Inheritance lets us
inherit attributes and methods from another class. Polymorphism uses those methods to perform
different tasks.
Ex: Let’s look at a class that will be used to represent a rectangle with the concepts we just
learned.
public class Rectangle
{
public Rectangle()
width = w;
height = 0;
width = w;
height = h;
return height;
return width;
void someSound()
System.out.println(“Screech”);
public Cat ()
System.out.print(“Meow”);
super.someSound();
public Garfield()
System.out.print(“Lasagna”);
{
public static void main(String [ ]args)
Recursion
Basics of Recursion
Note: The topic of recursion isn’t often found on free-response questions, it shows up in the multiple-
choice questions.
Recursion has a similar idea compared to a loop, but it functions a bit differently.
A recursive method has the characteristic to call a method itself. This is referred to as the recursive call.
To make sure that an infinite loop doesn’t occur the recursive method calls something called a base case.
Base case- Signal the execution to stop the recursion and return to each prior recursive call.
Say that you have a giant bag of small, and various colored candy. Since you are a programmer, and don’t
want to ruin your set up you decide that you need an algorithm. You will eat the random candies one at a
time until you find the candy with your favorite color. Once you found your favorite colored candy, you will
eat the same colors you ate before, but in a backward order.
Say the order that you eat the candies is red, blue, orange, blue, and green. Green is considered the based
case. You will then continue to eat, and will choose the blue, orange, blue, and red candies respectively.
The recursion is now complete.
Let’s look at some code to help simplify this further:
done eating;
else
Even though there are no loops used the logic, and the behavior is similar to that of loops. There is a
forward, and backward progression.
The base case is used to help stop the recursion just in case.
It’s often more common to use a for loop, but this is an alternative.
There is a lineup of football players, and they have numbered jerseys. Say you want to traverse the array to
find the position of the person that has the 9 on their jersey.
Code:
// The code above is for if the entire array has already been traversed, it
return -1;
//if the next item found in the array matches, then return it
if(nums[currentIndex] == key)
return currentIndex;
//or you need to step past the current item in the array, and keep searching
If we continue to use our example of football players it would look something like this:
Tying it up:
Recursion will make sure that the task is accomplished, even though it might not actually go
according to plan.
When the base case is reached, the execution of the current method is complete, and the
process repeats all the way back to the initial recursive call.