AP Computer Science A Ultimate Guide
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:
//this is a short comment
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 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.
This includes spaces!!
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.
Ex: numOfSides, or testScores
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.
Remember that when a programmer writes in Java, these lines of code are understood by a Java development environment.
An interpreter is used to change this code into binary(zeros and ones) which is what the computer understands.
This process is called compiling.
We use IDEs to write out code, or interactive development environments.
The code will be checked for programming errors.
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.
There are 2 ways to produce an output on the screen:
Using System.out.print;
Using System.out.println;
What’s the difference?
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:
System.out.println(“Quotes are used because a string is being printed. Otherwise it will simply print whatever is put in the brackets.”);
If you want to put a line break in a piece of code just use \n.
Ex:
System.out.print(“The first line\nThe second line”)
To create an identifier we need to assign a value to the identifier.
Note: type identifier = data;
Ex: int side1 = 2;
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.
Assignment statements DON’T print anything out as output!
Whenever data is associated with an identifier, it’s referred to as a variable.
Ex:
int myFavoriteNumber = 22;
myFavoriteNumber = 78;
System.out.print(“My favorite number is “ + myFavoriteNumber);
Output: My favorite number is 78
Important things to remember:
Once a variable is assigned a given type, it can’t be changed.
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.
Primitive Data- The basic type of data.
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.
**Character(**char)- It represents a single character that can be represented on a computer. It includes any character that you type on the keyboard. All the way from letters, numbers, spaces, and special characters. char values are stored with the use of single quotation marks or an apostrophe.
Note: The different operators that are used in Java are the +. - , ,/, and %.
The plus sign is used for addition.
Ex:
sumOfSides = side2 + side3;
The subtraction sign is used for subtraction.
Ex:
differenceOfSides = side1 - side3;
The asterisk or the star is used for multiplication.
Ex:
side1 * side2 = productSide;
The slash, or (/) is used for division.
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.
Negative numbers also work out the same way.
The only way to get over this portable is with casting.
Casting- A process in which data is forced to look like another type of data to the compiler.
System.out.print(3 - (double) (4)/5);
System.out.print( 3 - 4/(double)5);
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.
Ex: x++;
is the same as x = x+1;
Decrement operator(- -)- This decreases the value of a number by one.
Ex: x- - ;
is the same as x = x -1;
Other Shortcut Commands:
Shortcut Command | Equivalent Command |
---|---|
|
|
|
|
|
|
|
|
|
|
Object- A data type that is created in Java.
There is a class that is used to build more objects in Java specifically.
Classes have instance fields or data that belong to objects and methods that are used to help change the data.
This store's common numbers used in mathematical calculations and methods to have mathematical functions.
These methods are static.
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.*
We don’t need to create the objects in this class.
Here are the main ones used on the AP Exam:
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);
c. double chocAmount = 14.0/5.0;
//chose between these 3 options
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.
A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.
Here are some commonly used methods for the AP Exam:
Ex: Consider the following code segment, What will be the value of n?
String s = “This is the beginning”;
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.
Object- A data type that is created in Java.
There is a class that is used to build more objects in Java specifically.
Classes have instance fields or data that belong to objects and methods that are used to help change the data.
This store's common numbers used in mathematical calculations and methods to have mathematical functions.
These methods are static.
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.*
We don’t need to create the objects in this class.
Here are the main ones used on the AP Exam:
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);
c. double chocAmount = 14.0/5.0;
//chose between these 3 options
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.
A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.
Here are some commonly used methods for the AP Exam:
Ex: Consider the following code segment, What will be the value of n?
String s = “This is the beginning”;
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.
An if statement is just like it sounds. It’s a conditional statement that is used in Java to help control the flow of the program.
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.
You won't get to go if you don’t clean your room.
The else statement in the example below is used for what results to produce when the if condition isn’t being satisfied.
Ex:
int num1 = 4, num2 = 5;
if( num1 == num2)
System.out.print(“The numbers are the same.”);
else
System.out.print(“The numbers aren’t the same”);
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.
Values that can be compared using boolean statements:
==
(equal)
!=
(not equal)
<
(less than)
<=
(less than or equal to)
>
(greater than)
>=
(greater than or equal to)
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 and
||
- 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.
Ex: What will be the truth value of (! p && ! q) || (p || q)?
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.
Truth Table for combinations of Boolean Conditions:
A | B | A&&B | A||B | !A | !B | !(A&&B) | !A||!B |
---|---|---|---|---|---|---|---|
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 |
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.
This loop cycles through again and again, while the condition is considered true.
It’s similar to the if statement.
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.
So an infinite loop isn’t desirable in all situations.
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)
Let’s look at our paintbrush example again.
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.
This is just another type of loop and is just as effective as a while loop. The only difference is that one of the loops may make the code more simplified than the other.
Since this loop needs more components, it can help to avoid an infinite loop in some situations.
Here are some steps for how a for loop executes:
The initializer will start first and it will start the loop off.
The conditions will be checked to see if they are true or false.
The statements will execute.
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.
Once the value turns false the loop ends.
Ex:
for(int num = 1; num <= 22; num++)
System.out.println(num);
//Explanation: The loop above will show every number and the output on the screen on separate lines.
Ex:
for( int num = 1; num <= 3; num++)
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 :)
Differences between the 2:
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.
What to Expect on the AP Exam:
Concepts covered on the AP CSA Exam | Concepts not on the AP CSA Exam | |
---|---|---|
Primitives | int, double, boolean | short,long,byte,char,float |
Increment/Decrement Operators | x++,x-- | ++x,- - x |
Logical Operators | ==,!=,<,>,<=,>=,&&,||,! | &,|,^,<<,>>,>>> |
Conditional Statements | *if/else,****for,***while | *switch,****break,***continue, do/while |
Miscellaneous | ?:(ternary operator)User inputJavaDoc comments |
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.
A class is stored on your computer in a file.
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.
Ex: A class that calculated GPA may be called GradePointAvg, or GPA.
public class GradePointAvg
{
}
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.
It helps to set up the rest of the class.
The class above would be saved as GradePointAverage.java
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.
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:
public class Saturday
{
wake up method;//includes alarm times
eat breakfast method; // includes the ingredients, and calories
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.
While the driver class shortens, the object class expands.
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.
Header- It’s used to define the function of the method.
Constructor- They set an object's initial values for instance variables.
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.
Structure for a method:
Visibility returnType methodName(param1, param2)
The visibility is if the method is public or private.
The return type, specifies the type of data that will be returned from the methods after its commands are executed.
The method name, is the name of the method.
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.
Precondition- A comment that is intended to inform the user more about the condition of the method and guarantees it to be true.
Note: On the AP Exam, the precondition shows up as a comment above the method. It’s the program's job that calls the method not to pass parameters that violate the precondition.
Ex(Precondition):
/** precondition- a and b are positive integers*
*/
public int sum(int a, int b)
{
}
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):
public int sum100(int a, int b)
{
<code>
//postcondition- returns 100, if sum if greater than 100, or the value of the sum
if( sum < 100)
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.
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.
To create an object, you need to instantiate it using the corresponding class.
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.
Aggregate class- Made up of other data, and instances of other classes.
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 is useful for when you need data, and information from another class to use in another class. You would need to create a copy of the object so that it can be used in the specific class.
Note: When received as a parameter, primitive data is actually copied, while object data will receive a new reference to the object itself. Primitives are copied by value, objects are copied by reference.
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.
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- A data structure that makes it easier to handle similar types of data.
Arrays can store primitive or object data types.
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.
Primitives and Objects play a huge role in setting up an array. Use these steps to set up your array effectively.
The best way to teach this concept is by example, which is what we will walk through.
Decide on the types of data that will be stored in the array.
int [] <identifier> = new int [<array size>];
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.
int [] <identifier> = {<data1>, <data2>, <datan>}
Note: Square brackets are used to show that an array is present. While curly brackets indicate an initializer list, just like the examples above.
Ex: Create an array called testGrades that stores 5 test grades.
int[] testGrades = new int [5];
As mentioned before each data point will be stored with its unique index.
To create an array with data, you need to instantiate it.
Ex: If you score a 95 on the first test
testGrades[0] = 95;
Create an array with all the 5 scores at once:
int [] testScores = {90, 80, 100, 85, 92};
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
for( int index = 0; index < testGrades.length ; index++)
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.
A key tool to use when going through arrays is to use an enhanced-for-loop.
Ex: Calculate the average of 5 test grades
int total = 0, len = testGrades.length;
double average;
for (int index = 0; index < len; index++)
total += testGrades[index];
average = (double) total/len;
Ex: Calculate the average of 5 test grades using an enhanced-for-loop
int total = 0, len = testGrades.length;
double average;
for (int grade: testGrades)
total += grade;
average = (double) total/len;
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.
No variable is used to refer to the current index.
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.
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.
The most common searches are:
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.
The 2 searches above are referred to as search algorithms.
Note: On the AP Exam you will be asked to recognize these search algorithms and understand how they function.
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.
**Recursion- Technique that uses a method to call itself. ***View Unit 12
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 is a solution for this issue.
An ArrayList object is dynamically sized, it can become smaller or larger as elements are added or removed.
It can store multiple types of data without specific limits.
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.
Ex: Say you want to make an ArrayList called lunchBag.
ArrayList lunchBag = new ArrayList();
Unlike establishing an array, the number of objects or length isn’t set.
The way you access data within an ArrayList is different from that of Arrays.
Note: Bracket notation can’t be used, unlike in Array’s.
For example, say you want to return the second object, an Apple Object, from the ArrayList and store it in a variable.
Apple red = lunchBag.get(1);
Other useful methods include add, set, remove, and size.
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:
Integer n = new Integer (5);
Double x = new Double(6.1);
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 MIN_VALUE, and MAX_VALUE 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?
ArrayList list = new ArrayList();
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 array. The only case to use an import statement in an array would be when the array has specific elements that require import statements. | You have to have an important statement, java.util.ArrayList, or the full name of the package when you use the ArrayList. |
Elements can be accessed with index notation. Ex: | Different methods are used to access the ArrayList. Ex: |
Arrays can contain primitive data types(int, float, double, boolean, and char), and/or object data types. | ArrayLists can only be used to hold object references. |
They can only hold one specific type of element. Ex: If the array is said to hold only integers, then it stores only integers, not other types such as Strings. | Has the ability to hold a collection of objects.**However, this isn’t recommended** Ex: |
2D Arrays stands for 2-Dimensional Arrays.
A way to explain 2D Array’s is to use an example of a vending machine.
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 result of this is an “array of arrays”, or in other words a 2D array.
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]
Note: Remember that Indexes start at 0 on the AP Exam!
Note: Remember that Index numbers end at array.length-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:
Rows length: vendingMachine.length
This would tell you the number of slots that are across the machine.
Columns length: vendingMachine[0].length
This would tell you the length of the first column.
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:
/*The following class, Arr2d, is meant to represent a 2 dimensional array object.
the constructor will initialize, Arr2d using the number of rows and columns that have been passed
Choose the statement that will initialize the array in the constructor*/
public class Arr2D{
private int [][] arr;
Arr2D( int rows, int columns)
{
/*missing code*/
}
}
//what should the missing code be?
/*a. int [] arr = new String [rows][columns];
b. int [][] arr = new String [rows-1][columns-1];
c.arr = new String [rows][columns];
d.arr = new String [rows-1][columns-1];
e.int arr [][] = new String [rows][columns];
*/
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- 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.
This is referred to as multiple inheritance which ISN’T allowed in Java.
Overridden- When a new version of the code takes over from the old version.
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
{
private double width;
private double height;
public Rectangle()
{
width = w;
height = 0;
}
public Rectangle(double w, double h)
{
width = w;
height = h;
}
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
}
Ex: What output will this line of code produce?
class Animal
{
void someSound()
{
System.out.println(“Screech”);
}
}
class Cat extends Animal
{
public Cat ()
{
System.out.print(“Meow”);
super.someSound();
}
}
class Garfield extends Cat
{
public Garfield()
{
System.out.print(“Lasagna”);
}
}
public class Mainclass
{
public static void main(String [ ]args)
{
Garfield garfield = new Garfield();
}
}
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.
The best way to explain this is to use an example.
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:
eatCandy(color of current candy)
{
if(current candy color is green)
done eating;
else
eat more candy;
}
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.
Recursion is very useful when you want to solve problems, and the structure continues to repeat.
The base case is used to help stop the recursion just in case.
You can also use recursion to traverse arrays.
It’s often more common to use a for loop, but this is an alternative.
Let’s use an example to explain how this would work.
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:
public int findPosition(int nums[], int key, int currentIndex)
{
// The code above is for if the entire array has already been traversed, it
// shows that the number doesn’t exist
if(nums.length <= current Index)
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
Return findPosition(nums, key, currentIndex +1)
}
If we continue to use our example of football players it would look something like this:
int [] players = numPlayers;
int position = findPosition(players, 9,0);
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.
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:
//this is a short comment
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 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.
This includes spaces!!
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.
Ex: numOfSides, or testScores
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.
Remember that when a programmer writes in Java, these lines of code are understood by a Java development environment.
An interpreter is used to change this code into binary(zeros and ones) which is what the computer understands.
This process is called compiling.
We use IDEs to write out code, or interactive development environments.
The code will be checked for programming errors.
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.
There are 2 ways to produce an output on the screen:
Using System.out.print;
Using System.out.println;
What’s the difference?
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:
System.out.println(“Quotes are used because a string is being printed. Otherwise it will simply print whatever is put in the brackets.”);
If you want to put a line break in a piece of code just use \n.
Ex:
System.out.print(“The first line\nThe second line”)
To create an identifier we need to assign a value to the identifier.
Note: type identifier = data;
Ex: int side1 = 2;
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.
Assignment statements DON’T print anything out as output!
Whenever data is associated with an identifier, it’s referred to as a variable.
Ex:
int myFavoriteNumber = 22;
myFavoriteNumber = 78;
System.out.print(“My favorite number is “ + myFavoriteNumber);
Output: My favorite number is 78
Important things to remember:
Once a variable is assigned a given type, it can’t be changed.
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.
Primitive Data- The basic type of data.
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.
**Character(**char)- It represents a single character that can be represented on a computer. It includes any character that you type on the keyboard. All the way from letters, numbers, spaces, and special characters. char values are stored with the use of single quotation marks or an apostrophe.
Note: The different operators that are used in Java are the +. - , ,/, and %.
The plus sign is used for addition.
Ex:
sumOfSides = side2 + side3;
The subtraction sign is used for subtraction.
Ex:
differenceOfSides = side1 - side3;
The asterisk or the star is used for multiplication.
Ex:
side1 * side2 = productSide;
The slash, or (/) is used for division.
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.
Negative numbers also work out the same way.
The only way to get over this portable is with casting.
Casting- A process in which data is forced to look like another type of data to the compiler.
System.out.print(3 - (double) (4)/5);
System.out.print( 3 - 4/(double)5);
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.
Ex: x++;
is the same as x = x+1;
Decrement operator(- -)- This decreases the value of a number by one.
Ex: x- - ;
is the same as x = x -1;
Other Shortcut Commands:
Shortcut Command | Equivalent Command |
---|---|
|
|
|
|
|
|
|
|
|
|
Object- A data type that is created in Java.
There is a class that is used to build more objects in Java specifically.
Classes have instance fields or data that belong to objects and methods that are used to help change the data.
This store's common numbers used in mathematical calculations and methods to have mathematical functions.
These methods are static.
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.*
We don’t need to create the objects in this class.
Here are the main ones used on the AP Exam:
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);
c. double chocAmount = 14.0/5.0;
//chose between these 3 options
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.
A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.
Here are some commonly used methods for the AP Exam:
Ex: Consider the following code segment, What will be the value of n?
String s = “This is the beginning”;
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.
Object- A data type that is created in Java.
There is a class that is used to build more objects in Java specifically.
Classes have instance fields or data that belong to objects and methods that are used to help change the data.
This store's common numbers used in mathematical calculations and methods to have mathematical functions.
These methods are static.
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.*
We don’t need to create the objects in this class.
Here are the main ones used on the AP Exam:
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);
c. double chocAmount = 14.0/5.0;
//chose between these 3 options
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.
A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.
Here are some commonly used methods for the AP Exam:
Ex: Consider the following code segment, What will be the value of n?
String s = “This is the beginning”;
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.
An if statement is just like it sounds. It’s a conditional statement that is used in Java to help control the flow of the program.
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.
You won't get to go if you don’t clean your room.
The else statement in the example below is used for what results to produce when the if condition isn’t being satisfied.
Ex:
int num1 = 4, num2 = 5;
if( num1 == num2)
System.out.print(“The numbers are the same.”);
else
System.out.print(“The numbers aren’t the same”);
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.
Values that can be compared using boolean statements:
==
(equal)
!=
(not equal)
<
(less than)
<=
(less than or equal to)
>
(greater than)
>=
(greater than or equal to)
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 and
||
- 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.
Ex: What will be the truth value of (! p && ! q) || (p || q)?
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.
Truth Table for combinations of Boolean Conditions:
A | B | A&&B | A||B | !A | !B | !(A&&B) | !A||!B |
---|---|---|---|---|---|---|---|
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 |
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.
This loop cycles through again and again, while the condition is considered true.
It’s similar to the if statement.
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.
So an infinite loop isn’t desirable in all situations.
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)
Let’s look at our paintbrush example again.
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.
This is just another type of loop and is just as effective as a while loop. The only difference is that one of the loops may make the code more simplified than the other.
Since this loop needs more components, it can help to avoid an infinite loop in some situations.
Here are some steps for how a for loop executes:
The initializer will start first and it will start the loop off.
The conditions will be checked to see if they are true or false.
The statements will execute.
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.
Once the value turns false the loop ends.
Ex:
for(int num = 1; num <= 22; num++)
System.out.println(num);
//Explanation: The loop above will show every number and the output on the screen on separate lines.
Ex:
for( int num = 1; num <= 3; num++)
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 :)
Differences between the 2:
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.
What to Expect on the AP Exam:
Concepts covered on the AP CSA Exam | Concepts not on the AP CSA Exam | |
---|---|---|
Primitives | int, double, boolean | short,long,byte,char,float |
Increment/Decrement Operators | x++,x-- | ++x,- - x |
Logical Operators | ==,!=,<,>,<=,>=,&&,||,! | &,|,^,<<,>>,>>> |
Conditional Statements | *if/else,****for,***while | *switch,****break,***continue, do/while |
Miscellaneous | ?:(ternary operator)User inputJavaDoc comments |
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.
A class is stored on your computer in a file.
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.
Ex: A class that calculated GPA may be called GradePointAvg, or GPA.
public class GradePointAvg
{
}
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.
It helps to set up the rest of the class.
The class above would be saved as GradePointAverage.java
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.
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:
public class Saturday
{
wake up method;//includes alarm times
eat breakfast method; // includes the ingredients, and calories
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.
While the driver class shortens, the object class expands.
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.
Header- It’s used to define the function of the method.
Constructor- They set an object's initial values for instance variables.
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.
Structure for a method:
Visibility returnType methodName(param1, param2)
The visibility is if the method is public or private.
The return type, specifies the type of data that will be returned from the methods after its commands are executed.
The method name, is the name of the method.
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.
Precondition- A comment that is intended to inform the user more about the condition of the method and guarantees it to be true.
Note: On the AP Exam, the precondition shows up as a comment above the method. It’s the program's job that calls the method not to pass parameters that violate the precondition.
Ex(Precondition):
/** precondition- a and b are positive integers*
*/
public int sum(int a, int b)
{
}
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):
public int sum100(int a, int b)
{
<code>
//postcondition- returns 100, if sum if greater than 100, or the value of the sum
if( sum < 100)
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.
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.
To create an object, you need to instantiate it using the corresponding class.
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.
Aggregate class- Made up of other data, and instances of other classes.
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 is useful for when you need data, and information from another class to use in another class. You would need to create a copy of the object so that it can be used in the specific class.
Note: When received as a parameter, primitive data is actually copied, while object data will receive a new reference to the object itself. Primitives are copied by value, objects are copied by reference.
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.
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- A data structure that makes it easier to handle similar types of data.
Arrays can store primitive or object data types.
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.
Primitives and Objects play a huge role in setting up an array. Use these steps to set up your array effectively.
The best way to teach this concept is by example, which is what we will walk through.
Decide on the types of data that will be stored in the array.
int [] <identifier> = new int [<array size>];
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.
int [] <identifier> = {<data1>, <data2>, <datan>}
Note: Square brackets are used to show that an array is present. While curly brackets indicate an initializer list, just like the examples above.
Ex: Create an array called testGrades that stores 5 test grades.
int[] testGrades = new int [5];
As mentioned before each data point will be stored with its unique index.
To create an array with data, you need to instantiate it.
Ex: If you score a 95 on the first test
testGrades[0] = 95;
Create an array with all the 5 scores at once:
int [] testScores = {90, 80, 100, 85, 92};
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
for( int index = 0; index < testGrades.length ; index++)
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.
A key tool to use when going through arrays is to use an enhanced-for-loop.
Ex: Calculate the average of 5 test grades
int total = 0, len = testGrades.length;
double average;
for (int index = 0; index < len; index++)
total += testGrades[index];
average = (double) total/len;
Ex: Calculate the average of 5 test grades using an enhanced-for-loop
int total = 0, len = testGrades.length;
double average;
for (int grade: testGrades)
total += grade;
average = (double) total/len;
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.
No variable is used to refer to the current index.
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.
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.
The most common searches are:
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.
The 2 searches above are referred to as search algorithms.
Note: On the AP Exam you will be asked to recognize these search algorithms and understand how they function.
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.
**Recursion- Technique that uses a method to call itself. ***View Unit 12
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 is a solution for this issue.
An ArrayList object is dynamically sized, it can become smaller or larger as elements are added or removed.
It can store multiple types of data without specific limits.
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.
Ex: Say you want to make an ArrayList called lunchBag.
ArrayList lunchBag = new ArrayList();
Unlike establishing an array, the number of objects or length isn’t set.
The way you access data within an ArrayList is different from that of Arrays.
Note: Bracket notation can’t be used, unlike in Array’s.
For example, say you want to return the second object, an Apple Object, from the ArrayList and store it in a variable.
Apple red = lunchBag.get(1);
Other useful methods include add, set, remove, and size.
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:
Integer n = new Integer (5);
Double x = new Double(6.1);
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 MIN_VALUE, and MAX_VALUE 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?
ArrayList list = new ArrayList();
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 array. The only case to use an import statement in an array would be when the array has specific elements that require import statements. | You have to have an important statement, java.util.ArrayList, or the full name of the package when you use the ArrayList. |
Elements can be accessed with index notation. Ex: | Different methods are used to access the ArrayList. Ex: |
Arrays can contain primitive data types(int, float, double, boolean, and char), and/or object data types. | ArrayLists can only be used to hold object references. |
They can only hold one specific type of element. Ex: If the array is said to hold only integers, then it stores only integers, not other types such as Strings. | Has the ability to hold a collection of objects.**However, this isn’t recommended** Ex: |
2D Arrays stands for 2-Dimensional Arrays.
A way to explain 2D Array’s is to use an example of a vending machine.
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 result of this is an “array of arrays”, or in other words a 2D array.
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]
Note: Remember that Indexes start at 0 on the AP Exam!
Note: Remember that Index numbers end at array.length-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:
Rows length: vendingMachine.length
This would tell you the number of slots that are across the machine.
Columns length: vendingMachine[0].length
This would tell you the length of the first column.
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:
/*The following class, Arr2d, is meant to represent a 2 dimensional array object.
the constructor will initialize, Arr2d using the number of rows and columns that have been passed
Choose the statement that will initialize the array in the constructor*/
public class Arr2D{
private int [][] arr;
Arr2D( int rows, int columns)
{
/*missing code*/
}
}
//what should the missing code be?
/*a. int [] arr = new String [rows][columns];
b. int [][] arr = new String [rows-1][columns-1];
c.arr = new String [rows][columns];
d.arr = new String [rows-1][columns-1];
e.int arr [][] = new String [rows][columns];
*/
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- 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.
This is referred to as multiple inheritance which ISN’T allowed in Java.
Overridden- When a new version of the code takes over from the old version.
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
{
private double width;
private double height;
public Rectangle()
{
width = w;
height = 0;
}
public Rectangle(double w, double h)
{
width = w;
height = h;
}
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
}
Ex: What output will this line of code produce?
class Animal
{
void someSound()
{
System.out.println(“Screech”);
}
}
class Cat extends Animal
{
public Cat ()
{
System.out.print(“Meow”);
super.someSound();
}
}
class Garfield extends Cat
{
public Garfield()
{
System.out.print(“Lasagna”);
}
}
public class Mainclass
{
public static void main(String [ ]args)
{
Garfield garfield = new Garfield();
}
}
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.
The best way to explain this is to use an example.
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:
eatCandy(color of current candy)
{
if(current candy color is green)
done eating;
else
eat more candy;
}
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.
Recursion is very useful when you want to solve problems, and the structure continues to repeat.
The base case is used to help stop the recursion just in case.
You can also use recursion to traverse arrays.
It’s often more common to use a for loop, but this is an alternative.
Let’s use an example to explain how this would work.
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:
public int findPosition(int nums[], int key, int currentIndex)
{
// The code above is for if the entire array has already been traversed, it
// shows that the number doesn’t exist
if(nums.length <= current Index)
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
Return findPosition(nums, key, currentIndex +1)
}
If we continue to use our example of football players it would look something like this:
int [] players = numPlayers;
int position = findPosition(players, 9,0);
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.