AP Computer Science Study Guide
Created by Philip La
Welcome to the AP Computer Science Study Guide. Let's jump right in.
Table of Contents
1. Comments2. Intro to Strings
3. Variables
4. Primitive Data types
5. Using Mathematical Operators
6. The Math Class
7. Random Class
8. Intro to Conditionals
9. Objects
10. Naming Conventions
11. Advanced Conditionals Statements
12. Arrays
13. A more in depth look at strings
14. 2D Arrays
15. Array list
16. Inheritance and Polymorphism
17. Recursion
Intro to Strings
- String is the line of text, object in java, defined by the String class.
- String concatenation - Use
+
operator which adds multiple strings or number - Escape Sequence
\n
and \"
will be the escape sequence you will used most frequently.
Variables
- Variables in math and science represents something useful. In Computer Science, a variable is an identifier of a memory location.
- Location's value can be modified.
Primitive Data Types
int
= integer (-2, 147, 9, ...)
double
= floating point number, twice as much memory than float
boolean
= true/false
char
= single character
- All primitive types and memory cost
int
4 bytes
byte
1 bytes
short
2 bytes
long
8 bytes
double
8 bytes
float
4 bytes
char
2 bytes
- String is not a primitive type.
Using Mathematical Operators
- PEMDAS
- Operators:
+
,-
,*
,/
,%
(modulus - gets the remainder),=
(assign NOT EQUAL) - Parentheses overrides the operation order
- Defining a variable:
- Casting is converting from one data type to another.
- More operators
double square = (int)98.28; // Becomes 98
++
increment
--
decrement
+=
add then assign
-=
subtract then assign
*=
multiply then assign
/=
divide then assign
%=
get the reminder then assign
The Math Class
- Java has a built in math class that can deal with mathematical operations that are more complex than simple operation.
- Assume
num
is a declared variable
Math.operation(your parameter);
int abs(int num) // returns absolute value
double pow(double num, double power) // returns number to the power
double sqrt(double num) // returns square root of positive number
double random() // returns number between 0.0 & 1.0
Random Class
Random generator = new Random();
generator.nextInt(n); //return 1 to n-1
generator.nextDouble(); // returns same as math double random()
Intro to Conditionals
- if/else
- switch
- while
- do-while
- for
Equality Operators
==
means equals (= is the assignment operator)
!=
means not equal to
Relational Operator
>
, <
meaning greater than or less than
>=
, <=
means greater tha nor equal to or less tahn or equal to
Logical Operators
!
means not
Example: !true // means not true or false
&&
means and
Example: if (i > 5 && i < 10) // i has to be between 5 and 10 to be true
||
means or
Example: if (i < 0 || i > 1) // i has to be less than 0 or greater than 1 to be true
The if statement
- This statement will do the next thing if the contents in the parentheses is found to be true. Otherwise, the statement will be skipped.
Example:
if (cuteness > 5) {
girl.askForNumber();
}
The else statement
- This statement provides a secondary path of execution when an `if` clause evaluates to false.
Example:
if (housing != livesWithParents) {
girl.giveRealNumber();
} else {
girl.giveRandomNumber();
}
The while statement
- If the statement is true, it will continue to run the code until it is false.
- Beware of infinite loops.
Example:
int n = 1;
int endPoint = 10;
while (n <= endPoint) {
System.out.println(number);
n++;
}
Sentinel Value
- Sentinel, or "flag value" is a special value. It is usually provided to end a program.
The for statement
- The for statement provides a compact way to iterate over a range of values.
for (initialization; termination; increment) {
statement(s)
}
- When using this version of the for statement, keep in mind that:
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the termination expression evaluates to false, the loop terminates.
- The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Examples:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
for (int i = 0; i < 50; i++) {
System.out.println("I will not throw paper planes in class");
}
The switch statement
- The switch statement can have a number of possible execution paths.
Example:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
Objects
- What's the point?
- Reuse code, break down problem solutions, divide and conquer, avoid errors.
- A good object will be a thing, not an action. Example: Triangle, Snowman
- Anatomy of a Class
- Class Name
- Class Data
- Constructor (sets the initial data)
- Method declarations (what the class does)
- Visibility (aka scope)
- public: anything outside of the class
- private: can only be used within the class
- protected: not used at this time
Naming Conventions
- With multiple words:
- Classes: Capital first letter
- Methods: lower case first letter
- Variables: lower case first letter
- Constants: ALL_CAPS_WITH_UNDERSCORES
allWordsAfterFirstCapitalized
Advanced Conditional Statements
String Comparison
Remember String is an object.
string1 == string2
tests for reference equality and is for testing whether two strings are the same object. Use string1.equals(string2)
to test for value equality.
The Comparable interface contains only one method, compareTo, which takes an object as a parameter and returns an integer. If you need comparison functionality, you should implement the comparable interface. The String class implements the Comparable interface. Strings are compared character by character. Each character is encoded and stored in binary.
I the first characters are the same, then the next ones are compared and son. This basically does an alphabetization. Think of the string in the parenthesis as "the OTHER string".
Example:
String s1, s2; // s1 and s2 are assigned values
int result = s1.compareTo( s2 );
if ( result > 0 ) {
System.out.println( s1 + " is greater" );
} else if ( result < 0 ) {
System.out.println( s2 + " is greater" );
} else {
System.out.println( "equal" );
}
Float Comparison
It's a general rule that floating point number should never be compared like (a==b), but rather like (abs(a-b) < delta) where delta is a small number. A floating point value having fixed number of digits in decimal form does not necessary have fixed number of digits in binary form.
Character Comparison
Character values are numbers in the Unicode character set. They are in order, but upper and lowercase is seperator, so try not to use a>b.
Arrays
- Arrays are objects used to group and organize data. They are a sequence of values of the same type.
- The values held in an array are called array elements.
- An array stores multiple values of the same type (the element type).
- The element type can be a primitive type or an object reference.
- Thus, we can create an array of integers or an array of characters, or an array of string, objects, etc.
- In Java, the array itself is an object.
- Mistakes
- Bound Errors - modified elements beyond the array
- Uninitialized arrays
- Unfilled arrays null reference
- Use constants to show array length
- Use the length method to always avoid bound errors.
final int POWER = 5;
int[] powerLevels = new int[POWER];
Example:
for (int index = 0; index < array.length; index++) {
// do something here
}
- The array starts at 0 (remember value 1 is at location 0)
- The array goes to the length of the array
- Bound error is avoided by using less than evaluation
Example:
// for each digit in the array numbers, goes through the entire array
for (int digit: numbers) {
// do something here
}
A more in depth look at strings
Primitive Data Type - Char
- Char is a primitive data type. Example:
char letter = 'a';
String is an array of chars.
Methods of the String Class
- int length() - length of the string
- String substring(int from, int to) - returns String from to to-1
- String substring(int from) - return string from all the way to the end of the string
- int indexOf(String str) - returns index of first found str. returns -1 if not found.
- char charaAt(int index) - returns character at given index
- int compareTo - compares two strings
2D Arrays
- A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of arrays of arrays).
Try the following:int[][] multi = new int[5][10];
... which is a short hand for something like this:int[][] multi = new int[5][]; multi[0] = new int[10]; multi[1] = new int[10]; multi[2] = new int[10]; multi[3] = new int[10]; multi[4] = new int[10];
Note that every element will be initialized to the default value for int, 0, so the above are also equivalent to:int[][] multi = new int[][]{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
- Looping through 2d arrays:
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
// do something here
}
}
//I'd recommend j < array[i] here. Nothing
//changes on this case, but it would bring
//some trouble if the second dimension of the
//array was not the same for every case.
- The first for iterates over the array of five int arrays, that's why i goes from 0 to 4 and the array's length is 5. The second for iterates over the indexes of the int contained on the first array (the one with length 5). This arrays have a length of 10 elements.
Array List
- Dynamically changes size depending on what is needed
- Allows you to specialize on the ArrayList<String> or ArrayList<Integer> etc.
- The Wrapper Class:
- Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. So, there is an Integer class that holds an int variable, there is a Double class that holds a double variable, and so on. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.
- As you are aware, In Java not everything is an Object. There are primitive types such as int ,double float etc. So if you wanted to use a primitive type in place of Object i.e. if a method expects an Object but you need to send in a primitive type, without Wrapper classes this wouldn't be possible. Take for instance the Map interface. The put(Object,Object) method takes Objects as both key and value. If you, for example wanted to store a mapping between an integer value 1 (int i=1) to an Object, without wrapper classes this wouldn't be possible. Wrapper classes are used to represent primitive values when an object is required.
Inheritance and Polymorphism
- Subclass - class that is extension of the larger class
- Superclass - class above a class
- Subclasses - define more specific behaviors, Is-A-Relationship
- To inherit the functionality of superclass, use the key word
extends
Example:
public class Object extends SuperClass {
// do something here
}
Recursion
-
What is recursion?
- Recursion is when the method directly or indirectly invokes itself.
Example:
public int factorial (int x) {
if (x > 1) {
//recursive case:
return factorial(x-1) * x;
} else /*base case*/
return 1;
}
}
Following the code when it is factorial(3):
Comments
// This is a short comment.