AP CSA Java Notes
AP CSA Java Notes
Accessible methods from the Java library that may be included in the exam
Class Constructors and Methods Explanation
String Class
String(String str) Constructs a new String object that represents the same sequence of
characters as str
static double sqrt(double x) Returns the positive square root of a double value
static double random() Returns a double value greater than or equal to 0.0 and less than 1.0
ArrayList Class
int size() Returns the number of elements in the list
E remove(int index) Removes element from position index, moving elements at position
index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1
from size; returns the element formerly at position index
Object Class
boolean equals(Object other)
String toString()
o Helpful Algorithms
▪ Generating random integers
▪ Divisibility
▪ Place value for integers
▪ Rounding doubles
o Helpful Algorithms
▪ Traversing a String
▪ Reversing a String
▪ Search a String
▪ Count occurrences in a String
▪ Replace letters in a String
• Arrays
o Examples
▪ Creating an array, size of an array
o Helpful Algorithms
▪ Traversing an array
▪ Find max/min of an array
▪ Average of an array
▪ Search an array
▪ Find the mode of an array
▪ Sort an array (selection and insertion)
• ArrayLists
o Helpful Algorithms
▪ Find max/min of an ArrayList
▪ Average of an ArrayList
▪ Search an ArrayList
▪ Find the mode of an ArrayList
▪ Sort an ArrayList (selection)
• Methods and Examples
The Math Class •
•
Helpful Algorithms
Home
Output: Output:
9 5.7
Exponents
static double pow(double base, double exponent) returns the value of the first parameter raised
to the power of the second parameter.
static double sqrt(double x) returns the positive square root of a double value.
Output: Output:
0.7 10.0
Random Number Generation
static double random() returns a double value greater than or equal to 0.0 and less than 1.0
//Produces a double in the range [0,9) //Produces a double in the range [4,9)
//Produces an int in the range [0,9] //Produces an int in the range [4,9]
Helpful Algorithms
Generate a random number from Minimun value to Maximum value
Generate a random number from
int r = (int)(Math.random() * (max – min + 1)) + min;
min to max
Divisibility
int num = 100
int divisor = 5;
boolean isDivisible;
Determine if a number is divisible
by another number isDivisible = num % divisor == 0;
-OR-
if(num % divisor == 0)
isDivisible = true;
else
isDivisible = false;
Digits
int num = 5278;
//ones place
System.out.println(num / 1 % 10);
//tens place
Identify the nth digit of an integer. System.out.println(num / 10 % 10);
//100s place
System.out.println(num / 100 % 10);
//nth place
System.out.println(num / (int)(Math.pow(10, n-1)) % 10);
int num = 5278;
if (num == 0)
{
System.out.println(num);
Stripping off the last digit one at a }
else
time.
{
while (num > 0)
{
System.out.print(num % 10); //print last digit
num = num / 10; //strip off last digit
}
}
Rounding
double num = 12345.6531;
You can create a String object by using a String literal or the String constructor
Output: Output:
length method
Output: Output:
Length is 5 Length is 4
equals method
boolean equals(String other) returns true if this equals other; returns false otherwise
Output: Output:
false false
true
true
substring Methods
/* /*
0 1 2 3 4 5 0 1 2 3 4
|G|u|c|c|i| |T|e|a|m|
*/ */
Output: Output:
cc am
Gucci eam
ci Team
indexOf Method
int indexOf(String str)returns the index of the first occurrence of a String, returns -1 if string not found.
/* /*
0 1 2 3 4 0 1 2 3
|G|u|c|c|i| |T|e|a|m|
*/ */
Output: Output:
2 3
3 0
-1 0
compareTo method
int compareTo(String other) returns the alphabetic difference between two strings.
Helpful Algorithms
Basic String Traversal
System.out.println(myString.substring(i, i + 1);
}
Output:
G
u
c
c
i
System.out.println(reverse);
Output:
droW
System.out.println(reverse);
Output:
droW
Search a String
if(twist.substring(i, i + 1).equals("e")){
foundE = true;
}
}
Contains e: true
int countARE = 0;
if (lyric.substring(i, i + 3).equals("Are")){
countARE++;
}
}
Output:
if(letter.equals("e")){
makeLeet += "3";
}
else{
makeLeet += letter;
}
}
System.out.println(makeLeet);
Output:
I_Am_L33t_Gam3r
Remove all occurrences of a substring in a String
index = temp.indexOf(toFind);
Output:
Pama Cal
•
Arrays
Methods and Examples
• Helpful Algorithms
• Home
(The size of an array cannot be changed)
/* /*
Creating an Empty Array of ints with Creating an initialized array of
size 5 Strings
*/ */
myArray[0] = 5;
myArray[3] = 2;
00 11 22 33 44 00 11
5 0 0 2 0 "Bill" "Paxton"
Length of an Array
/* /*
Creating an Empty Array of ints Creating an initialized array
with size 5 of Strings
*/ */
System.out.println(myArray.length); System.out.println(myArray.length);
Output: Output
5 2
•
Arrays
Methods and Examples
• Helpful Algorithms
• Home
(The size of an array cannot be changed)
Helpful Algorithms
Traversing an Array
You can access each element of an array by using a for-loop or an enhanced for loop.
Output: Output:
John Sinatra
Paul Martin
George Davis
Ringo
RingoGeorgePaulJohn
Find Max and Min in Array
Basic For Loop Enhanced For Loop
int[] nums = {3, 2, 6, 8, 100, 4, 1}; int[] nums = {3, 2, 6, 8, 100, 4, 1};
System.out.println(average); System.out.println(average);
Output: Output:
3 3
Searching an Array
int target = 4;
boolean found = false;
Output:
int currMaxCount = 0;
int mode = nums[0];
int count = 1;
int currNum = nums[i];
Output:
while (k > 0 && temp < arr[k - 1]) // Loop until "hole" is in correct place.
{
arr[k] = arr[k - 1]; // Move next data element to "hole".
k--; // Set k to new position of "hole".
}
add methods
boolean add(E obj) appends obj to the end of the list; returns true.
void add(int index, E obj) inserts obj at position index (0 <= index <= size) moving
elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size.
integerList.add(i);
}
integerList.add(3, 200);
0 1 2 3 4 5 6 7 8
|110|111|112|113|114|115|116|117|118|
0 1 2 3 4 5 6 7 8 9
|110|111|112|200|113|114|115|116|117|118|
size method
int size() returns the number of elements in the list.
ArrayList<Integer> integerList = new ArrayList<Integer>();
System.out.print(integerList.size() + "\t");
integerList.add(i);
}
System.out.print(integerList.size());
Output:
0 10
get method
beatles.add("George");
beatles.add("Paul");
beatles.add("Ringo");
beatles.add("John");
System.out.println(beatles.get(1));
System.out.println(beatles.get(3));
List:
0 1 2 3
|"George"|"Paul"|"Ringo"|"John"|
Output:
Paul
John
set method
beatles.add("George");
beatles.add("Paul");
beatles.add("Ringo");
beatles.add("John");
Output:
remove method
E remove(int index) removes element from position index, moving elements at position index + 1 and
higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position
index
beatles.add("George");
beatles.add("Paul");
beatles.add("Pete");
beatles.add("John");
beatles.remove(2);
beatles.add("Ringo");
Helpful Algorithms
Traversing an ArrayList
ArrayList<String> languages = new ArrayList<String>();
languages.add("Spanish");
languages.add("French");
languages.add("English");
Spanish
French
English
a max of 100 and min of 1*/ a max of 100 and min of 1*/
System.out.println(average); System.out.println(average);
int currMaxCount = 0;
int mode = nums.get(0);
int count = 1;
int currNum = nums.get(i);
int target = 4;
boolean found = false;
int target = 4;
int count = 0;
Remember, if you need to remove all or multiple occurrences of a value from an ArrayList, going forward could cause
you to skip some items. When the remove(int index) ArrayList method is called, it removes the item, shifts
all the values at a higher index to down to a lower index (one less than their current index).
Selection Sort for an ArrayList
Sorts from lowest to highest
/** Inserts one Integer value into an ArrayList that is sorted into ascending
(non-decreasing) order */
/** Inserts one Integer value into an ArrayList that is sorted into ascending
(non-decreasing) order */