0% found this document useful (0 votes)
26 views9 pages

Sparky Notes AP CS 2015

The AP CS Java Sparky Notes provide a comprehensive overview of Java programming concepts, including primitive data types, objects, strings, loops, arrays, and ArrayLists. Key topics include the use of equality and relational operators, methods for string manipulation, iterative loops, array operations, searching algorithms, and sorting techniques. The document emphasizes best practices and common pitfalls, such as aliasing and the importance of using appropriate methods for comparisons.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views9 pages

Sparky Notes AP CS 2015

The AP CS Java Sparky Notes provide a comprehensive overview of Java programming concepts, including primitive data types, objects, strings, loops, arrays, and ArrayLists. Key topics include the use of equality and relational operators, methods for string manipulation, iterative loops, array operations, searching algorithms, and sorting techniques. The document emphasizes best practices and common pitfalls, such as aliasing and the importance of using appropriate methods for comparisons.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

AP CS Java Sparky Notes

Hip, Hip, Array!!!

BR2016

~ Primitive data ~ Equality and Relational


(int, double, boolean, char) == equal to
!= not equal to
*Passed by “value” not “reference” < less than
Examples: <= less than or equal to
int x; //has value of 0 > greater than
>= greater than or equal to
int y=5; // integers have a range -231 to 231 - 1
double a; //has value 0.0 Logical Operators
&& AND – both parts must be true
double b = 4.2; || OR – at least must be true
char topGrade = ‘A’; //single quote marks for char ! NOT – negate
boolean checker = true; DeMorgan’s Laws:
int min = Integer.MIN_VALUE; //-231 !(p && q) = !p || !q
int max = Integer.MAX_VALUE //231 !(p || q) = !p && !q
if/else/else if: Short Circuiting:
remember, the “else” goes with the closest “if” clause && - once a false is reached, all is false
Order of Operations: || - once a true is reached, all is true
! is always first , then ( ) *, /, %, +,- enumerated type – “category” data
(% returns remainder. Use for even/odd check.) enum season {winter, spring, summer, fall};

~ Objects ~ Passed by “reference” not “value.”


anything that is not Primitive (String, Arrays, any object you create) is an object
Be careful of “aliasing” with all objects.
AP CS Java Sparky Notes basics Page 1
~ Strings ~
Key Points:
 index from 0 to .length()-1
 to compare strings - use .equals .equalsIgnoreCase or .compareTo (do NOT use != or ==)
 Strings is an immutable object - its methods cannot change the content of a string object.
 Be Aware/Careful of aliasing - when two variables point to the same memory location.
Examples:
String str1 = “compsci”;
String str2 = new String (“hi”); // notice two ways to instantiate a String object
String str3; //creates a null string of size 0
str2 = str3 //causes aliasing - str2 now points to the same memory location as str1
if (str2 == str3) // == test for alias and it will return true. == is NOT the same as .equals
Frequently Used Methods:
.length() returns the length (or number of characters) of the string
.equals(s) returns true or false when comparing two strings
.equalsIgnoreCase() returns true or false when comparing two strings and ignores case difference
.substring (x,y) returns a section of the string from the beginning of x to the beginning of y
.substring (x) returns a section of the string from x to length-1
.charAt() returns the character at index x
.indexOf(s) returns the index of the String s in the string, searching from index 0
.indexOf(s,x) returns the index of the String s in the string, searching from index x
.trim() removes leading and trailing whitespaces
.replaceAll(x,y) returns a new String with all x changed to y
.toUpperCase() returns a new String with all uppercase characters
.toLowerCase() returns a new String with all lowercase characters

AP CS Java Sparky Notes Strings Page 2

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); }

AP CS Java Sparky Notes Loops Page 3


~ Arrays ~
Arrays - can contain any data type (primitive or object) but all must the same data type
(i.e. no mixing)
to find length of array: nameOfArray.length
to print elements of an array: Arrays.toString(nameOfArray) or a for-loop, or your own toString

~ 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.

int [] example2 = {1,2,5,6}; int [][] example4 ={ {1,2,3},{4,5,6}};


creates an array with specific values creates a 2D array 2rows x 3col with specific values.

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] + “ “); }

AP CS Java Sparky Notes Array Intro Page 4

SOME ARRAY ACCESS EXAMPLES ~ Generate random integer from 1 to n ~


int r = (int)(n * Math.random()) + 1;

~ to find min (in 1D array) ~ ~ random numbers (used in array) ~


// setting min to largest int number possible; search 0 to end
// pre-condition: array contains more than 0 elements //code example will fill an array with random integer
public static double findMin (int[] a) { values in range 50-100 inclusive
int aMin = Integer.MAX_VALUE; Random generator = new Random();
for (int i=0; i<a.length; i++){ int [] numArray = new int [100]
if (a[i] <aMin) for (int index= 0; index<=numArray.length-1; index++)
aMin = a[i]; numArray[index] = (int)generator.nextInt(51) + 50;
}
return aMin; ~ to find average (in 2D array) ~
} // pre-condition: array contains more than 0 elements
~ to find max (in 1D array) ~ public static double findDoubleAverage (double[][] a) {
// setting max to 0th element; search element #1 to end int count=0;
// pre-condition: array contains more than 0 elements double sum = 0;
public static double findMax (double[] a) { for (int row=1; row<a.length; row++) {
double aMax = a[0]; for (int col=1; col<a[row].length; col++) {
for (int i=1; i<a.length; i++){ sum +=a [row][col];
if (a[i] > aMax) count++;
aMax = a[i]; }}
} return sum/count; }
return aMax;
}
AP CS Java Sparky Notes Array Methods – find max, **random, average Page 5
~ Searching Array – Sequential or Linear ~ ~ Searching Array - Binary~
 sequential search compares every element for a key.  binary search is a “divide and conquer” approach.
 Not good for a large data set  Array must be in order (See Sorting on Page 7)
 import java.util.Arrays.*;
public static int search(int [ ] num, int key)
{  Frequently used methods that search a specified array for a
for (int index = 0; index < num.length; index++) key value:
{ public static int binarySearch (int[] a, int key)
if ( num[index] = = key )
public static int binarySearch (double[] a, double key)
return index; //We found it!!!
}
return -1; //We did not find!!! o The array must be sorted before making this call.
} o If not found, returns a -1.
o If found, returns the index where “key” is located.
o If it is not sorted, the results are undefined.
AP CS – must know ~ Code Example – Array sort & search ~
A. Operations on data structures int arr1[] = {30, 20, 5,12,55};
1. Traversals
2. Insertions
Arrays.sort (arr1); //from standard library to sort array
3. Deletions // now arr1 = {5,12,20,30,55}
B. Searching
1. Sequential int searchVal = 12;
2. Binary int retVal = Arrays.binarySearch(arr1,searchVal);
C. Sorting //will return a 1 (index 1)
1. Selection // if not found, binarySearch returns a -1
2. Insertion System.out.println (“The index of element 12 is : “+ retVal);
3. Mergesort

AP CS Java Sparky Notes Searching Arrays Page 6

~ 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 Sorting Algorithms for Arrays Page 7


~ArrayList ~
The java.util.ArrayList class provides resizeable-array and implements the List interface.
 You must import java.util.ArrayList;
 ArrayList index starts at 0 and ends at .size()-1 Initialize and add elements to ArrayList:
 ArrayLists hold objects. Java will automatically convert ArrayList<String> example5 = new ArrayList<String>();
primitive types to an object using the Wrapper class. example5.add (“java”);
example5.add(0,”C”);
example5.add(2,”run”);
 Syntax to build an array list of integers:
// example5 now contains: C java run
ArrayList<Integer> nameOfList = new ArrayList<Integer>();
3 ways to print an ArrayList:
 Frequently used ArrayList methods:
Name Use
add(item) adds item to the end of the list //1. Using an iterator
ListIterator iterator = example5.listIterator();
add (index, item) adds item at index and shifts other items
while (iterator.hasNext())
set (index, item) puts item at index
System.out.println(iterator.next());
get (index) returns the item at index
size() returns the # of items in the list
remove() removes an item from the list ** //2. Using a for loop with the .get() method
for int(i=0; i<example5.size();i++)
clear() removes all items from the list
System.out.println(example5.get(i);
** Warning - removing items from an ArrayList
//3. Using a print output statement
if you process items right to left (low index to high index) and
System.out.println(example5);
remove an element of an ArrayList, you can miss processing an
item.

AP CS Java Sparky Notes Array Lists Page 8

~ Compare double, int and objects ~


1. Compare integers, use == != < > <= >=
if (5 > 3) System.out.println (“5 is greater than 3”);
2. Compare doubles, use < > <= >= with a tolerance and absolute value
double d1 = 5.3, d2 = 5.31;
if ( Math.abs(d1-d2) <= .01) System.out.println(“within tolerance”);
3. Compare objects
o Strings – use the .equals() or .equalsIgnoreCase() method.
Returns true if the strings contain the same contents, false if not
The .equals() method is of the class Object: public boolean equals (Object other)
String favorite = “Comp Sci”;
if favorite.equals(“Comp Sci”) System.out.println(“the strings are the equal”);
Note: Using == with Strings tests for aliases
o a.compareTo(b) method : public int compareTo (T other)
compareTo is part of the Comparator interface and can be used to compare two strings lexicographically (alphabetical
order) and returns
0 if “a” and “b” are equal in their order
+ integer if “a” comes after “b” in their order
- integer if “a” comes before “b” in their order
o compare(a,b) method: public int compare (T obj1, T obj2)
compare compares values of two objects. It is implemented as part of the Comparator interface. You define what is
compared and returned. compare(a,b) is an example of implementation of an abstract method. (see page 12)
compare(a,b) returns a
0 if obj1 and obj2 are equal
+ integer if obj1 >obj2,
- integer if obj1<obj2
AP CS Java Sparky Notes Compare int, double, String, objects Page 9
Method Header format: visibility static returnType name (parameters)
~Visibility: Public, Private, and Protected ~ ~ Class Order ~
The concepts of public and private apply to the class as a whole,
not to the individual objects of the class. // 1. class name
o private features of a class can be directly accessed only
within the class’s own code. public static Account {
o public features can be accessed in client classes using // 2. instance variable definition
appropriate name-dot prefix. int accountNumber;
o Instance variables are almost always private. double balance;
~ static (optional) ~ String name;
static modifier - an attribute belongs to a variable or
class as a whole, not to an individual object instance of that // 3. constructor (like method header but no return type)
class. // constructor name matches class name
~ returnType ~ public Account (int acct, double bal, String nm)
return statement returns a reference to an object of a {
class. The data type must match the return type.
accountNumber = acct;
~ void ~
If there is no returnType, use the reserved word void balance = bal;
~ final ~ name = nm;
final is a fixed value for a variable. }
// 4. Methods – accessor, mutator
*File name and class name MUST match in name and case.
public double getBalance()
* main or runner is in a separate file/class
{ return balance;}}

AP CS Java Sparky Notes Class & Methods Page 10

~ Math Class ~ ~ Data Formatting ~


Math.pow(double base, double power) - returns double 1. Escape Sequences (some)
Math.sqrt(double num) - returns double \t Insert a tab in the text at this point
\n Insert a new line in the text at this point
Math.random() - returns double from [0,1) \’ Insert a single quote in the text
Math.min (a, b) - returns minimum of a and b. if a and be are \” Insert a double quote in the text at this point
both int, returns int. If a and b are both double, returns double. \\ Insert a \ in the text at this point
Math.max (a, b) - same as above but max 2. printf
Math.abs(a) - returns absolute value of a. If a is int, return int. If Begins with a % and ends with a converter. The converter is a character
a is double, returns double. indicating the argument type to be formatted.
import java.util.Formatter;
Math.PI – final value for pi d decimal (integer)
f float
Math Class methods can be combined in one line of code. n new line
double pi = Math.PI;
To find the min of three numbers a,b,c: System.out.printf (“%f%n”, pi); // 3.141593
int min = Math.min ( Math.min(a,b) , c); System.out.printf (“%.3f%n”, pi); // 3.142
3. DecimalFormat class
Steps to generate a random integer from 1 to 6 (die) User specified “mask” for data formatting.
int die1 = (int) (Math.random() *6) + 1; 0 will force a 0, # will round the output to specified.
1) Math.random returns a double [0,1). import java.text.DecimalFormat;
2) Multiply both end values by 6  possible values [0,6). DecimalFormat fmt = new DecimalFormat(“0.###”);
3) Convert to an integer  0,1,2,3,4,5 double someNumber = Math.random()*100;
System.out.println (fmt.format(someNumber));
4) Add one to every possible value  1,2,3,4,5,6 NumberFormat money = NumberFormat.getCurrencyInstance();
double someMoney = 20.16;
System.out.println(money.format(someMoney)); //$20.16
NumberFormat percent = NumberFormat.getPercentInstance();
double somePercent = 10.6;
System.out.println(percent.format(somePercent)); //10.6%

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.

Uses of Recursion: solving maze, solving Towers Of Hanoi,


Sorting (Merge Sort and Quick Sort), graphics.

AP CS Java Sparky Notes Interface, Abstract Methods, & Recursion Page 12

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();

AP CS Java Sparky Notes Inheritance Page 13


Example
o Polymorphism is the ability of an object to public interface Vegetarian {}
take on many forms. public class Animal {}
o The most common use of polymorphism in public class Deer extends Animal implements Vegetarian{}
OOP occurs when a parent class reference is
used to refer to a child class object. The Deer class is to be polymorphic since it has multiple
o Any Java object that can pass more than one inheritances.
IS-A test is considered to be polymorphic. Deer IS-A Animal
Deer IS-A Vegetarian
Deer IS-A Deer
Deer IS-A Object

The following are legal:


Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All reference variables d,a,v,o refer to the same Deer
object.

AP CS Java Sparky Notes Polymorphism Page 14

 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

AP CS Java Sparky Notes Exceptions Page 15


Javadoc is a tool that generates html documentation (similar to the Javadoc code Example Shell:
reference pages at java.sun.com) from Javadoc comments in the /** Description of MyClass
code. *
* @author Favorite TeacherOne
Javadoc Comments * @author Favorite TeacherTwo
 Javadoc recognizes special comments /** .... */ which are * @version 1.2a January 2016
highlighted blue by default in Eclipse (regular */
comments // and /* ... */ are highlighted green). public class MyClass
{ /** Description of input1 */
 Javadoc allows you to attach descriptions to classes,
public int input1;
constructors, fields, interfaces and methods in the generated /** Description of MyClass()
html documentation by placing Javadoc comments directly *
before their declaration statements. * @throws myException
Description of myException
Javadoc Tags */
 Tags are keywords recognized by Javadoc which define the type public MyClass() throws myException
of information that follows. { // code would be here for myException }
 Common pre-defined tags:
o @author [author name] - identifies author(s) of a class or /** Description of myMethod(int a, String b)
interface. *
o @version [version] - version info of a class or interface. * @param a Description of a
o @param [argument name] [argument description] - describes * @param b Description of b
* @return Description of c
an argument of method or constructor.
*/
o @return [description of return] - describes data returned by public Object myMethod(int a, String b)
method (unnecessary for constructors and void methods). {
o @exception [exception thrown] [exception description] - Object c;
describes exception thrown by method. // code would be here for myMethod
o @throws [exception thrown] [exception description] - same return c;
as @exception. }
}
AP CS Java Sparky Notes java docs & code example Page 16

AP CS Java Sparky Notes OTHER Page 17

You might also like