Sparky Notes AP CS 2015
Sparky Notes AP CS 2015
BR2016
Iterative Loops ~
~ for ~ ~ while ~ ~ do - while ~
Test condition at beginning of loop Test condition at beginning of loop Test condition at end of loop
Good for specific # of iterations Good for unknown # iterations Good for unknown # iterations
Runs at least once
for loop syntax & example: while loop syntax:
for (initial ; test; change) do - while syntax:
while (someConditionIsTrue){
for (int i=0; i<str.length(); i++){ //do something do {
//do something; } } //do something
while loop example: } while(condition);
~ for each ~ int count=0;
Good with arrays while (grade >=0){ do - while example:
sum += grade; do{
for each loop syntax & example: sum += grade;
for (type variable: someList) count++; }
count++; }
while (grade >=0);
String [] someList;
for (String item: someList) {
System.out.println(item); }
~ 1D-Array~ ~ 2D-Array ~
int [] example1 = new int[10]; int [][] example3 = new int[10][4];
creates an array of size 10, index 0 to 9, filled with creates a 2D array of size 10 rows and 4 columns,
zeros. filled with zeros.
print 1D-array: either use a for loop or toString print 2D-array in row-major order
method. // (row control variable is in outer loop)
for (int row=1; row<myArray.length; row++) {
Arrays.toString(example2); for (int col=1; col<myArray[row].length; col++) {
System.out.print( myArray[row][col] + “ “);
for (int cnt=0; cnt < example2.length; cnt++) }
System.out.println();
System.out.prinln (example2[cnt] + “ “); }
~ Sorting Algorithms ~
Arrays.sort (arrayToBeSorted) method that sorts an array in ascending/descending order
There are many algorithms but ALL require swapping elements.
Swapping elements in an array requires 3 assignment statements.
Efficiency (big O notation): classify algorithms efficiency is based on input size (n) and identify best and
worst case:
Selection (best/worst: O(n2)) Insertion (best: O(n) worst: O(n2)) MergeSort (best/worst: O(n log n))
Bubble (best: O(n) worst: O(n2))
Selection Sort Insertion sort MergeSort
•select smallest element, put in 0th start with two elements, put in order. Add • Split array in half, recursively sort the
position. Select next smallest element, another element and insert it into the proper first half and the second half, then merge
put in 1st position, etc. location of the “subset”, continue until done. two sorted halves.
• Inefficient on large lists. More efficient than selection. • Invented by John vonNeumann
AP CS Java Sparky Notes Misc: Math Class and Data Formatting Page 11
Interface & Abstract methods Recursion – the process of a method calling itself.
o An Interface is a collection of abstract methods that Always identify a base case and make sure you will reach it!
you must implement in your class.
Example1: Factorial
o An abstract method is a method that is declared but is Factorial: 5! = 5 * 4 * 3 * 2 * 1
not implemented (no code) in the interface but must be n! = n * (n-1) * (n – 2) * … * 2 * 1
implemented in the class that “implements” the
interface. public static int factorial (int n) {
if (n == 1) return 1; //base case
return n * factorial (n-1); //recursive call
// interface is in one file (ExampleInterface.java) }
public interface ExampleInterface { Example2: sum 1 to n
public int setSomething(); } //abstract method public int sum (int n) {
int result;
if ( n == 1) result = 1; //base case
// implementation of interface in your class else result = n + sum(n-1); //recursive call
public class Example implements ExampleInterface { return result; }
//instance variables and constructor here
public int setSomething() {return 10;} Direct recursion is when a method calls itself (like above
examples). Indirect recursion is when a method calls another
method, eventually resulting in the original method being called
again.
o Subclass (or child)- A class that is derived from another class (parent) and inherits all fields and public and protected methods from its super
class.
o Java only allows for single inheritance (a child can have only one parent)
o All classes in Java are descendants of Object.
o extends is the keyword used to inherit properties of a class
o super keyword is similar to this keyword. It is used to differentiate the members of superclass from members of the subclass if they have the
same name.
o this is a keyword that references the currently executing object.
~ PARENT CLASS ~ ~ CHILD CLASS ~
public class Bicycle { public class MountainBike extends Bicycle {
// the Bicycle class has three fields // the MountainBike subclass adds one field
public int cadence;
public int seatHeight;
public int gear;
public int speed; // the MountainBike subclass has one constructor
// the Bicycle class has one constructor public MountainBike(int startHeight, int startCadence,
public Bicycle(int startCadence, int startSpeed, int startGear) { int startSpeed, int startGear) {
gear = startGear;
super(startCadence, startSpeed, startGear);
cadence = startCadence;
speed = startSpeed; } seatHeight = startHeight; }
// the Bicycle class has four methods // the MountainBike subclass adds one method
public void setCadence(int newValue) {cadence = newValue;} public void setHeight(int newValue) {
public void setGear(int newValue) { gear = newValue; } seatHeight = newValue; }}
public void applyBrake(int decrement) { speed -= decrement; } Instantiation: public Bicycle MomBike = new Bicycle(2,4,6);
public void speedUp(int increment) { speed += increment; } } public MountainBike myBike = new MountainBike();
An exception is an event, which occurs during the execution of a Exception Handling Syntax Rules:
program, that interrupts the normal flow of the program. It is an error 1. The statements in the try{} block can include:
thrown by a class or method reporting an error in code Statements that work.
The 'Throwable' class is the superclass of all errors and exceptions Statements that might throw an exception
in the Java language. 2. One or several catch{} blocks follow the try block
Exceptions can be handled by using 'try-catch' block. Try block
Sometimes there can be no catch{} block
contains the code which is under observation for exceptions. The
3. Each catch{} block says which type of Exception it catches.
catch block contains the remedy for the exception. If any exception
occurs in the try block then the control jumps to catch block.
Code Example:
Exceptions to watch out for:
Scanner scan = new Scanner (System.in);
A NullPointerException is thrown when an application is trying to
use or access an object whose reference equals to null.. int num;
IndexOutOfBoundsException - indicate that an index of some sort System.out.println(“enter an integer: “);
(such as to an array, to a string, or to a vector) is out of range. try
ArrayIndexOutOfBoundsException – indicates and index of an { num = scan.nextInt();
array is out or range.
System.out.println(“your number is: “+num); }
ArithmethicException – indicates a divide by zero.
catch (InputMismatchException ex)
IllegalArgumentException - indicate that a method has been
passed an illegal or inappropriate argument
{ System.out.println (“You entered bad data. “); }
InputMismatchException – is thrown by a Scanner to indicate that
the token retrieved does not match the pattern for the expected type,
or that the token is out of range for the expected type