FLVS AP Computer A Science Terms

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Identity equality

Refers to whether two objects are actually the same object.

Java Exceptions Throws

Runtime Exceptions ArithmeticException Thrown when an exceptional arithmetic condition has occurred. For example, if an attempt is made to divide an integer by zero, an instance of this class will be thrown. ArrayIndexOutOfBoundsException Thrown when an array is accessed with an illegal index, that is, an index that is either negative or greater than or equal to the length of the array. ClassCastException Thrown when an attempt is made to cast an object to a subclass of which it is not an instance. For example, if an Object is initialized to an Integer and an attempt is then made to cast it to a String, an instance of this class will be thrown. IllegalArgumentException Thrown when a method is passed an illegal or inappropriate argument. For example, if, according to its signature, a method expects an int as its argument and a double is passed to it instead, an instance of this class will be thrown. NullPointerException Thrown when an attempt is made to treat a null object as if it were not null. For example, if an attempt is made to call the length instance method of a null object (as if it were a String), then an instance of this class will be thrown. IllegalStateException Thrown when a method is invoked at an illegal or inappropriate time, that is, when the Java environment or Java application is not in an appropriate state for the requested operation. (See below this table for more information.) NoSuchElementException Thrown when an Object that implements a certain kind of collection of objects uses an instance method that is designed to access the next object in the collection when in fact there are no more objects. (See below this table for more information.) Many answers are possible for each part. One possibility is provided in each case. System.out.println( 4 / 0 ); int[] a = new int[ 1 ]; System.out.println( a[ 1 ] ); Object a = new Integer( 1 ); System.out.println( (String)a );

Lossy conversion

"lossy conversion" may occur when a floating point number is assigned to a variable basically a float is converted to an int

Abstract class versus concrete

A class that implements all the interface abstract methods and uses the keyword implements in its class header is called a concrete class. A class may also implement more than one interface. An useful interface to implement is the Comparable<T> interface. It includes a compareTo() abstract method that, when properly implemented, allows you to easily compare and sort objects that are of the same reference type.

Integer

A number The largest acceptable integer is 231 - 1, that is, 2147483647. The version of Java used in this course employs 4 bytes of memory to store an integer, where each byte contains 8 bits. Each bit is a binary digit, and so there are 32 binary digits available to store an integer. But the topmost digit is used to store the sign — it is set to 0 for a positive integer or the number zero and 1 for a negative integer. So only 31 binary digits are used to store the absolute value of the integer. The largest integer that can be stored in 31 binary digits is 231 - 1, that is, 2147483647. Regardless of how many bytes are used to store an integer, the largest integer that any particular version of Java can store is always given by Integer.MAX_VALUE. Check this claim by entering this expression into the white box (taking care to use the exact mixture of uppercase and lowercase letters shown here) and clicking the Run button.

Method

A segment of code that performs a small, very specific task. Can be called functions or procedures. I will call it a function

Delimiter

A sequence of one or more character used to specify the boundary between separate, independent regions in plain text or other data streams. EXAMPLES commas name, me sd , dgs a new line for now, it is a white space LEARN MORE ABOUT IT

binary sort

A suitable definition (inspired by the sample code in Exercises 174 and 175) is as follows: public static int binarySearch( int[] array, int target ) { int high = array.length; int low = -1; int probe; while ( high - low > 1 ) { probe = ( high + low ) / 2; if ( array[ probe ] > target ) high = probe; else low = probe; } if ( low >= 0 && array[ low ] == target ) return low; else return -1; } We observe that, with the above definition, if target occurs more than once in array, then the index that is returned will always be that of the last occurrence. There are other ways to code a binary search that will consistently return another index in such a case (the index of the first occurrence, for example).

traversal

A traversal is simply an iteration through an array or an ArrayList. You can consider it similar to flipping through the pages of a book. While traversing the book, you can write down vocabulary words and their definitions to help build a glossary. Since a traversal involves iteration, it naturally will involve a loop of some sort. If you think back to when you first worked with arrays and ArrayLists, this makes perfect sense. Loops and data structures go hand in hand. THINK ABOUT IT we have been saying traverse through an array all this time without really knowing what it meant

Heading into the abstract

An abstract class may also contain abstract methods. An abstract method can only be contained in an abstract class. It also has no body but rather is just a skeleton shell of a method. In order to be usable, an abstract method must be overridden by a derived class of the abstract class. When only a shell is needed where nothing is defined for it, except public abstract methods or public static final initialized constants, then an interface is created. A regular class does not extend an interface, but rather implements it. An interface class may extend another interface class, however

Iterations and Recursions

Both Both iteration and recursion are based on control statements. Both iteration and recursion involve repetition. Both iteration and recursion involve a termination test. Both iteration and recursion gradually approach termination. Both iteration and recursion can occur infinitely. Iteration Iteration uses a loop statement (such as for). Iteration explicitly uses a repetition statement. Iteration terminates when the loop condition fails. Iteration modifies a counter, which eventually makes the loop continuation condition fail. Iteration becomes infinite if the loop continuation test never becomes false. Recursion Recursion uses a selection statement (such as if-else). Recursion uses repeated method calls. Recursion terminates when a base case is recognized. Recursion produces simpler versions of the original problem until the base case is reached. Recursion becomes infinite if the recursion step does not reach the base case.

Inheritance and Polymorphism STUDY GUIDE

Classes Class A class, each of whose instances represents the class of an object. The getClass method of the Object class returns a Class object. Object A class that is the direct superclass of every class that is not defined explicitly as the direct subclass of another. Vocabulary Class hierarchy The collection formed by a class and all its subclasses. Derived A class C is derived from a class D if D is the direct superclass of C. Extend A class C extends a class D if D is the direct superclass of C. Inherit A class inherits from all of its superclasses all their instance methods and other characteristics (but not their constructors) that are not private. The class has access to all these aspects of its superclasses without having to repeat their definitions or declarations in the class definition. Polymorphism The practice of declaring a variable to have a particular data type C and initializing it to an instance of a subclass of C. This has the effect of causing the variable to store an instance of the subclass while being treated within the program as if it stored an instance of the superclass. Subclass A class C is a direct subclass of a class D if and only if the definition of C includes the code "extends D". C is a subclass of D if and only if it is either a direct subclass of D or there is a chain of direct subclass relationships that begins with C and ends with D. Superclass A class C is the direct superclass of a class D if and only if the definition of D includes the code "extends C". C is a superclass of D if and only if it is either a direct superclass of D or there is a chain of direct superclass relationships that begins with C and ends with D. Notation extends The keyword that indicates that the class named to its left is a direct subclass of the class named to its right. super The keyword which, when applied to arguments, passes those arguments on to the constructor of the current class's direct superclass. When used in the definition of a class constructor, any super expression must be the first expression in the body of the constructor definition. Methods getClass An instance method of the Object class. When called on an Object object, returns an instance of the Class class that represents the object's class. getName An instance method of the Class class. When called on a Class object, returns a String that names the class represented by the object. toString An instance method of the Object class. When called on an Object object, returns a String that represents the object. Errors Cannot resolve symbol The error that results when, using polymorphism, a variable that is declared to have data type C and initialized to an instance of a subclass of C is subsequently referenced in the invocation of a method that is defined in the subclass but not in C. To avoid this error, cast the object to the subclass before invoking the method. Class cast exception The error that results when an attempt is made to cast an object to a class that is neither its actual class nor one of the superclasses of that class.

Bubble Sorting

Comparing every pair of adjacent values and reorganizing if one is smaller than the other. This is repeated until all the items in a list are organized.

Comparable T interface

Comparing reference variables in Java can be tricky. If you recall, equality has to be checked using an equals method, not the double equal sign (==) relational operator as one might expect. Java provides a Comparable<T> interface that includes an abstract compareTo method. Programmers can use it to identify how two objects of the same type compare based on a given criterion. basically when you want to compare a lot of things. Usually it works by returning zero if two objects are equal, a positive integer if the first object comes after the second, and a negative integer if the first object comes before the second.

Number systems

Binary-2 Octal-8 hex-16

Search Sorting Example with ArrayList Class/Interface

Exercise 188 A suitable definition is as follows: public static void selectionSort( Item[] array ) { int i, k, posmax; Item temp; for ( i = array.length - 1 ; i > 0 ; i-- ) { posmax = 0; for ( k = 1 ; k <= i ; k++ ) { if ( array[ k ].compareTo( array[ posmax ] ) > 0 ) posmax = k; } temp = array[ i ]; array[ i ] = array[ posmax ]; array[ posmax ] = temp; } } Exercise 189 A suitable definition is as follows: public static void selectionSort( ArrayList<Item> list ) { int i, k, posmax; Item temp; for ( i = list.size() - 1 ; i > 0 ; i-- ) { posmax = 0; for ( k = 1 ; k <= i ; k++ ) { if ( list.get( k ) .compareTo( list.get( posmax ) ) < 0 ) posmax = k; } temp = list.get( i ); list.set( i, list.get( posmax ) ); list.set( posmax, temp); } }

Tokens

Java handles the contents of a file as separate tokens (a single word, number or symbol), individual pieces of data filing sequentially along in a stream of information. The same Scanner class methods you used to accept user input from the keyboard next(), nextLine(), nextInt(), and nextDouble() can be used to pick tokens out of an input stream from a file.

What i should understand about the print class

Notice that a format specifier is imbedded within the String literal, essentially as a placeholder for a variable; it always starts with a percent sign (%) and ends with a converter (e.g., s, d, or f). The percent sign resembles the escape character (\) in that it alerts Java to not print what follows, but to do something different based on the sequence of characters. The converter is a character indicating the type of the argument to be formatted. Optional flags or specifiers can be sandwiched between the percent sign and the type. So the dissected format specifier consists of these parts. The leading percent sign (%) Optional flag or specifier (+, -,,) Field width (optional) A converter (s, d, or f)

Rules of the t interface

Now, according to the rules for writing a proper compareTo method, it must satisfy the following three rules: Return a negative number if value a is less than value b. Return a zero if a has the same value as b. Return a positive number if the value a is greater than the value of b. THIS IS NOT VERY DIFFICULT AT ALL.

List<E> instance methods ( a list that can hold a variety of things) (of the abstract e interface (not an abstract class) (think about it like other methods that are static but this one is slightly different))

Partial definition of the e interface public interface List<E> // inheritance not shown { boolean add( E x ); void add( int index, E x ); E get( int index ); E remove( int index ); E set( int index, E x ); int size(); // the next two methods are not in the AP Java subset Iterator<E> iterator(); ListIterator<E> listIterator(); // other methods not shown } Here we go boolean add( E x ) Effect: Extends the list by inserting x after the former last element and adjusts the size of the list. Return value: The boolean true. void add( int index, E x ) Effect: Extends the list by inserting x as a new element at the given index and, if there is an element at that index, moving it and any elements beyond that point one place to the right; adjusts the size of the list. Return value: None. Throws: An IndexOutOfBoundsException if index is negative or greater than the size of this list. E get( int index ) Return value: The element at the given index. Throws: An IndexOutOfBoundsException if index is negative or greater than or equal to the size of this list. E remove( int index ) Effect: Shortens the list by removing the element at the given index and moving any elements beyond that point one place to the left; adjusts the size of the list. Return value: The element formerly at the given index. Throws: An IndexOutOfBoundsException if index is negative or greater than or equal to the size of this list. E set( int index, E x ) Effect: Replaces the element at the given index by x. Return value: The element formerly at the given index. Throws: An IndexOutOfBoundsException if index is negative or greater than or equal to the size of this list. int size() Return value: The number of elements in this list. Iterator<E> iterator() Return value: An Iterator<E> object that will iterate over the elements in this list in proper sequence. ListIterator<E> listIterator() Return value: A ListIterator<E> object that will iterate over the elements in this list in proper sequence. Some important things to note: There are two essential features of the List<E> interface that distinguish it from other interfaces, namely: Elements in a List<E> can be referenced by index. A List<E> may contain duplicate elements. That is, the same object may appear several times. ALSO: arraylist implements the e interface, but we don't see exactly how because we also import the util instead of hardcoding it.

When the original way of declarations is wrong Try to make everything OOP

Previously, when you would use an array list, you would declare a variable to be of type ArrayList. For example: ArrayList<Integer> numList1 = new ArrayList<Integer>(); While it is written correctly, this code is not considered proper, as it lacks some flexibility. To make the code more in line with object-oriented programming practices, you should actually create the array like this: List<Integer> numList1 = new ArrayList<Integer>(); This makes numList1 to be of type List and reference an instance of an ArrayList. This provides better flexibility when using the numList1 variable. It can actually reference any type of list—not just the ArrayList.

Comparing objects using the t comparisonn interface (so you are comparing different attributes of your objects one by one)

The T that appears between angle brackets in the name of this interface is a formal type parameter, just like the E that appears in the name of the ArrayList<E> class. Each time we replace T by the name of a reference data type, we get an interface that prescribes a compareTo method that takes an argument of the data type in question. For example, a class implementing the Comparable<Person> interface must provide a method with return data type int and signature compareTo( Person p ), whereas a class implementing the Comparable<Building> interface must provide a method with return data type int and signature compareTo( Building b ).

More information on the comparable t interface

The built-in Java String class has a compareTo method because — as it happens — it implements the Comparable<String> interface. Since String is a built-in class, its compareTo method is already provided — we are not responsible for defining it. The designers of Java have seen to it that the compareTo method they have built into the language behaves in a way that faithfully reflects the extended lexicographical order, which is an extension of what is used when words are listed in order in a dictionary, for example.

Lexicographical sorting using a search algorithm (ascending in this case)

The definition is virtually identical to the one for sorting arrays of ints, the only differences being that the comparison in the inner for-loop must use the compareTo method instead of > and the variable temp must be declared as a String instead of an int. public static void selectionSort( String[] array ) { int i, k, posmax; for ( i = array.length - 1 ; i > 0 ; i-- ) { posmax = 0; for ( k = 1 ; k <= i ; k++ ) { if ( array[ k ].compareTo( array[ posmax ] ) > 0 ) posmax = k; } String temp = array[ i ]; array[ i ] = array[ posmax ]; array[ posmax ] = temp; } }

Important things to note about ARRAYS

The first index position within an array is 0, not 1. Also, the length of an array is static and does not change after the array is initialized. can only store one type of data ex. array of strings, array of ints, array of doubles

New algorithm for binary search

The following code uses a slightly different algorithm for a binary search in an ordered array of integers than the one we have been using so far: public static int binarySearch( int[] array, int target ) { int left = 0; int right = array.length - 1; int middle; while ( left <= right ) { middle = ( left + right ) / 2; if ( array[ middle ] == target ) return middle; if ( array[ middle ] > target ) right = middle - 1; else left = middle + 1; } return -1; } Describe one or more ways in which this algorithm is preferable to our previous binary search algorithm. Describe one or more ways in which our previous binary search algorithm is preferable to this one. Loading [Contrib]/a11y/accessibility-menu.js Exercise 180 With this algorithm it is no longer the case that, for a given size of array, the binary search always takes the same number of iterations. Because this algorithm checks whether or not array[ middle ] is the target, it is possible for the algorithm to terminate before the collection of possible array elements has been reduced to a single element. In fact, we could be lucky and hit the target on the very first iteration! In addition, a very minor increase in efficiency results from the fact that, on each iteration of the while-loop, the middle element is removed from consideration, thereby narrowing the field of possible elements somewhat more rapidly than the previous algorithm does. With the previous algorithm, each iteration of the while-loop involves only one comparison. With this algorithm, each iteration that does not result in termination of the algorithm requires two comparisons. The potential exists, therefore, for this algorithm to require twice as many comparisons as the previous algorithm. Since comparison of integers occurs almost — but not quite — instantaneously, the resulting decrease in efficiency would be barely detectable for all but the most enormous arrays. But if this algorithm were applied to arrays of Strings, say, comparisons of which are much more time-consuming, then possibly doubling the number of comparisons could really slow down the operation of the algorithm. In practice, the choice of a search algorithm involves more parameters than we have examined here. Issues that have an impact on the decision include these: how many elements are there likely to be in the arrays being searched? are there any patterns in the data? For example, does the target being looked for often appear early in the array? how time-consuming is the element-comparison process? It is often the case that a conclusion cannot be reached until a computer engineer performs a battery of trial runs using each of the candidate algorithms on collections of simulated data.

Handling tokens and streams in Java

The same Scanner class methods can be used to pick tokens out of an input stream from a file. It will have a delimiter of a white space.

Variables

Two types: primitive data types and refence variables Primitive-type explicitly defined Reference-type not explicitly defined

FUN FACTS

We are now in a position to tell you exactly what "iterable" means. In fact, it is almost laughably simple: for each reference data type E, Java provides a built-in interface, Iterable<E>, which is designed solely for the purpose of allowing the use of for-each loops on instances of classes that implement the interface. For each reference data type E, the ArrayList<E> class implements the List<E> interface (as we have just informed you), and the List<E> interface is a subinterface of the Iterable<E> interface. Consequently, for each reference data type E, the ArrayList<E> class implements the Iterable<E> interface, and that is why we can use for-each loops to iterate over the elements of an ArrayList<E> instance.

Implementing the interface

We now need a way of telling Java that a class contains the methods specified in the interface. We do so using the keyword "implements". If the definition of a class C overrides all the methods of an interface I and if C's class header includes the clause "implements I", then we say that class C implements interface I. Both conditions are required if C is to be a concrete class; it's not good enough just to override the interface's abstract methods — the implements clause has to be there too. So, for example, we could amend the definition of the StringIndex class on the previous page so as to make its relationship to the Incrementable interface apparent like this: public class StringIndex extends MyTestClass implements Incrementable { private String myString; private int myIndex; public StringIndex( String s ) { super( 0 ); myString = s; myIndex = 0; } public String subString() { return myString.substring( myIndex ); } public void increment() { myIndex++; } public void decrement() { myIndex--; } public void restart() { myIndex = 0; } } By declaring that StringIndex implements Incrementable we make it possible for instances of StringIndex to be stored in variables of type Incrementable, thereby making available all the benefits of polymorphism:

Casting

When you cast something as an int, the decimal is truncated. Can't save double as int. Can be done inversely though

String methods

equals()equalsIgnoreCase() toUpperCase()toLowerCase() compareTo()compareToIgnoreCase()

End of File (EOF)

files can be read using a while loop, as long as the EOF is not reached (no more tokens to read in the data stream)

Thinking about abstract

for example you have a load of t-shirts in your drawer an abstract class would define what a t-shirt SHOULD have a concrete class would literally be a t-shirt

For-each loops

for(String person : names) { System.out.println(person); } it is meant to iterate through a DATA STRUCTURE When reading the expression "for ( String name : names )" aloud, it is usual to add the word "each" after "for" and to read the colon as "in"; so the entire expression is read as "for each String name in names". Every for-each loop has four components, none of which may be omitted, as follows: for ( declaration : expression ) body for The Java keyword that, together with the presence of a colon (and the absence of semicolons) in the parenthesized code that follows, identifies this piece of code as a for-each loop. body The loop body: a statement or block of statements. This code is executed once during each iteration of the loop. declaration The loop variable declaration: the declaration of the variable to which each element of the array or collection that is the value of expression is assigned during successive iterations of the loop. (The declaration has the form of a data type — such as int, String, or boolean — followed by a variable, known as the loop variable.) expression The loop collection expression: a statement expression such that the value of the corresponding statement is either an array or some other collection that is "iterable". (This array or "iterable" collection is known as the loop collection.) (We remark that for-each loops are sometimes referred to as "enhanced for loops".) For now, we limit ourselves to arrays when it comes to for-each loop collections. As we advance further in this course, we will meet other kinds of collections to which for-each loops may be applied, and will specify more precisely in what sense they are "iterable". Things to note always in index order, cannot call iterating variable/ the index variable

Decendingn order

he only change necessary is to reverse the inequality sign in the condition of the if-statement in the inner for-loop: public static void selectionSort( int[] array ) { int i, k, posmax; for ( i = array.length - 1 ; i > 0 ; i-- ) { posmax = 0; for ( k = 1 ; k <= i ; k++ ) { if ( array[ k ] < array[ posmax ] ) posmax = k; } int temp = array[ i ]; array[ i ] = array[ posmax ]; array[ posmax ] = temp; } } Although it is not necessary in order to make the code work as intended, it would make the code easier for a human being to read and understand if each occurrence of the variable posmax in this code were replaced by one, such as posmin, that is more descriptive of its role in a descending order sort.

HOW TO DECLARE AN ARRAY-ints/doubles numeric

int [] intValues; intValues = new int[10]; or int maxIndex = 100; double [] doubleValues = new double[maxIndex];

More fun with interfaces

public interface Incrementable { public abstract void increment(); public abstract void decrement(); public abstract void restart(); } this is half correct but java wants us to simplify the script (the compiler understands the stuff but needs it in a different way, an even more simplified definition) public interface Incrementable { void increment(); void decrement(); void restart(); } no need for modifiers like abstract or public because interfaces by definition contain methods that are both public and abstract.

The modulus operator or remainder operator

remainder is kept, not the quotient when dividing with the %

Compiler

software used to translate program code written in a programming language to machine language for the computer to utilize Syntax=correct translation=correct coversion to machine language=correct output

A class contains the

source code (actual code)

Swapping and use of temporary variable

temp = source[ i ]; source[ i ] = source[posMax ]; //setting value of old value in max position to where the newly found max was (in its old position) source[ posMax ] = temp; //setting the value of the position of the max found in array to temp, which hen overwrites source [i], which is the last position in array (not ignored part) Notice that the swap looks similar to that used in bubble sort. It should, as the swap procedure is always the same when switching two elements in an array. Use of a temporary variable is key so values are not lost or overwritten.

Polymorphism

the ability to assign a different usage to a method

Lined class

uncompiled

Syntax error

violates rules of language

Casting

when you cast something after an operation ex. int()

more on exception handling

you could have runtime errors, but usually your java compiler catches those (basically you made some huge syntax error) or you could your own hand-written one! ASSERTIONS! yay so you can have an assertion that tells you if a precondition or postcondition is met. If not, then WOAH you have an error, so you can program the program to stop or just let the user know in the console that your program sucks

Practice question

½n(n - 1) the formula A programmer has written code that uses an insertion sort to sort an array into ascending order and then reports the amount of time taken. The code is executed on an array of 1,000 items that is already sorted into ascending order, and it takes 1.5 seconds. Approximately how long would it have taken if the array had initially been sorted into descending order? [Hint: Since an insertion sort operates in linear time on an already-sorted array, you should be able to make an estimate of how long each comparison takes. Use this figure to help you estimate the answer to the question.] Answer An insertion sort of an already-sorted array of 1,000 elements requires 999 comparisons. The time taken is 1.5 seconds. So the time required for a single comparison is about 1.5 / 999 seconds. Applying the same sort algorithm to the same array if it were initially in reverse order would require ½ × 1000 × 999 comparisons. The time required would therefore be about ½ × 1000 × 999 × 1.5 / 999, that is, 750 seconds.

HOW TO DECLARE AN ARRAY-string

String [] names; names = new String[10]; or String [] names = new String[10];

Notes about time with this particular algorithm

You may have noticed that if the array has n elements then the first iteration involves n - 1 comparisons, the second involves n - 2 comparisons, the third involves n - 3 comparisons, and so on until the last iteration which involves just 1 comparison. So the number of comparisons is (n - 1) + (n - 2) + ... + 1 It can be shown that this is equal to ½n(n - 1) comparisons. So, for example, the number of comparisons that must be made to complete a selection sort on an array of 1000 elements is exactly ½ * 1000 * 999 = 499,500. An important feature of a selection sort is that the number of comparisons is always the same for a given array length. It makes no difference, for example, if the array happens to be already sorted (see the last single stepper above). There are other sorting algorithms for which the initial ordering of the data can have a huge effect on the number of comparisons made.

data structure

a collection of information that is referred to by one name such as arrays and array lists

array

a data structure containing a single type of data (e.g. ints, Strings, etc.) which is accessed by index positions

Byte

a group of binary digits or bits (usually eight) operated on as a unit. a byte considered as a unit of memory size. Integer usually require two bytes a sign takes up one bit in java

A program consists of one or more

classes

No lines on a class

compiled

Design error/run time

compiles and runs, but the output is not what you want

binary versus sequential (Iterations)

Array size Sequential Binary k k log base 2 of (k)

Types of lists

Arrays Linked lists- a data structure that can hold an arbitrary number of objects in which each object points to the next link. Trees- a data structure hierarchy that grows from a single root module Array lists- a data structure which stores objects and allows / provides methods to add, delete, and retrieve indexed items.

BG on arrays

Arrays are structured, organized, and consecutively ordered. Items can be added, deleted, modified, or reorganized. Everything is located in an easily identifiable place in memory. All items in the list can be referred to by the same name. Entries in one list can be reassigned to another list.

Insertion Sorting

As you discovered in Exercise 192, the number of comparisons made by an insertion sort depends on the initial ordering of the source array. If the source array is already sorted then n - 1 comparisons are made, where n is the length of the array. If the array is sorted in reverse order, then the number of comparisons is the same as for a selection sort, namely, ½n(n - 1). For any other ordering of the source array, the number of comparisons is somewhere between these two extremes.

Modulus

Gives a remainder after division instead of the quotient

Content equality

Indicates whether two objects contain equal values.

Recursive solutions example

How would you count the number of digits in a number? For example, given the integer 1987532, how would you know the number contained seven digits? Think about it recursively and divide the problem into a smaller and smaller number. The number of digits in 1987532 is 1 plus the number of digits in 987532. The number of digits in 987532 is 1 plus the number of digits in 87532. The number of digits in 87532 is 1 plus the number of digits in 7532. The number of digits in 7532 is 1 plus the number of digits in 532. The number of digits in 532 is 1 plus the number of digits in 32. The number of digits in 32 is 1 plus the number of digits in 2. There is only one digit in 2. This is the nature of recursive solutions. Divide and conquer until you get down to a base case, then solve the problem in reverse. this whole divide and conquer business is a fairly bad descriptor of how to describe all of this. I would say repeating an action in order to get to a point where the action can no longer be executed, use the repetition before to solve until the initial question is answered. Think more about the recursive solution that you had to do in math class.

Blue jay

IDE (integrated development environment)

CompareTo method returns using T<interface>

If a and b are Strings, then the value of a.compareTo( b ) is a negative integer if and only if a precedes b in the extended lexicographical order; the integer zero if and only if a and b are the same string; a positive integer if and only if b precedes a in the extended lexicographical order.

Interfacing

If we wanted to have an array of pens and computers, we could not do so, as they do not belong to the same class hierarchy. However, if we move the write method to an interface, then we are able to create an array to contain both objects. An interface consists of abstract methods; therefore, the write method would be abstract. That means, for a class to use the interface, it must implement it. In the implementation, all abstract methods would be implemented. So a pen could write by using ink, and the computer could write by using its various methods. An interface is created when only a shell of a class is needed. Meaning it contains public abstract methods and/or public static final initialized constants. The methods are not defined and do not provide code for implementation. An interface is not extended by a regular class but rather is implemented. However, an interface class may extend another interface class. A class that implements all the interface abstract methods and uses the keyword implements in its class header is called a concrete class. A class may also implement more than one interface. Since interfaces are implemented, class hierarchies are not created. Rather, interfaces allow classes to organize and share methods that might be implemented differently, yet called by the same name.

Doubles

In Java, a variable of type double may store positive or negative floating point numbers with absolute values in the range 4.9 × 10-324 to 1.8 × 10308. decimal numbers that have more than seven digits to the left of the decimal point are printed in scientific notation.

About accepting array list for insertion sort

In the next exercise, we have in mind to define a sortArrayList static method that can be used to sort an ArrayList of any kind of "sortable" objects. From our recent experience, we know that this means the objects to be sorted should all be instances of the same class and that class should implement an appropriate Comparable interface. So the question is: How can we tell the Java compiler that our method is prepared to accept an ArrayList of any kind of objects implementing a Comparable interface? The answer is to use a complicated-looking — and, to be honest, rather ugly — modification to the method header. In this case, the header will be public static <T extends Comparable<T>> ArrayList<T> sortArrayList( ArrayList<T> source ). Most aspects of this header are already familiar to you: The method's name is sortArrayList. It takes one argument of type ArrayList<T> (but without telling us what "T" is), for which the variable source will be used in the body of the method definition. It returns a value of the same type as the input (still without telling us what "T" is). It is modified in the usual way by the keywords public and static. The unfamiliar part is the <T extends Comparable<T>> between the modifier keywords and the return data type. This is called a type bound; it is what actually tells us (and the Java compiler) what the mysterious "T" is. In English, it says, "T is any class that implements the corresponding Comparable<T> interface". You do not have to know about type bounds for the Advanced Placement examination and you will never have to write headers of this kind in an examination context. In the few places where we use them in this online course, we will always provide them for you and we will make an appropriate explanatory comment.

Object-oriented programming notes

Many program design considerations boil down to how to pass parameters to objects. Do you instantiate an object through the constructor's private instance variables, do you pass values directly to a method's parameter list, or do you use some combination? There are often different solutions to achieve the same goal; however, each choice has its own set of consequences for method design. Fortunately, these choices become less complicated because there are basically only four kinds of methods to worry about: accessors, mutators, getters, and setters.

YAYAYAYAYA Recursion

Method Trace: The trace of the numberOfDigits() method is shown below. The stack is represented on the left, showing the first unfinished method call at the bottom and the result of the base case at the top. After the base case is reached, evaluation of unfinished method calls resumes at the top of the stack and proceeds to the bottom. Recursive call 5: f(4) Recursive call 4: f(43) Recursive call 3: f(431) Recursive call 2: f(4312) Recursive call 1: f(43125) = 1 = 1 + f(43/10) = 1 + f(431/10) = 1 + f(4312/10) = 1 + f(43125/10) = 1 + f(4) = 1 + f(43) = 1 + f(431) = 1 + f(4312) return 1 return 1 + 1 = 2 return 1 + 2 = 3 return 1 + 3 = 4 return 1 + 4 = 5 The Stack Evaluation Do not let this confuse you when compared to the diagram shown in the Evaluation paragraph above. Just remember it is like stacking plates; the last one added to the stack has to be processed first when evaluation resumes. That is recursion! Practice: Be sure to type this method into BlueJ and run it with several different values of n. Do not forget to add a main method.

Introduction to Exception Handling

Most often, programmers are asked to perform basic unit testing and integration testing. It is through these two types of testing that we analyze our code daily, and, if we really want to do a detailed analysis, we go further and prove it by using more complex mathematical proofs. unit testing: the analyzing of small parts of a program (such as code fragments, methods, classes) integration testing: the analyzing of the interactions between parts of a program Frequently, in Java, this testing and analysis is performed using assertions and exceptions. For example, say you write a method to input elements into an array. After running your method, you test the array to see if it is full. If it is full, your method worked; however, if it is empty or only partially filled, then your method has failed. The statement that the array should be full would be your assertion. The checking (to see if the array is empty or full) is done to determine if your assertion is true or false. If full, your assertion was true and your method has passed unit testing for it. Otherwise, your assertion is false and your method has not passed, and an exception should be thrown. assertions: a statement that, at a certain point in program execution, must be true. If it is false, then the program has not performed correctly. exceptions: when a program does not perform correctly, an exception can be thrown that instructs Java to display a message explaining that an error has occurred.

Sequential versus binary searching (NOT SORTING AND DON'T CONFUSE WITH SEARCH SORTING)

Some practice questions Suppose that array is an array of ints (arranged in increasing order) and target is an int. Consider the follow two code segments, implementing a sequential search (on the left) and a binary search (on the right): int i = 0; boolean found = false; while ( !found && i < array.length ) { if ( array[ i ] == target ) { found = true; System.out.println( "Found at " + i ); } i++; } int low = -1, high = array.length, probe; while ( high - low > 1 ) { probe = ( high + low ) / 2; if ( array[ probe ] > target ) high = probe; else low = probe; } if ( low != -1 && array[ low ] == target ) System.out.println( "Found at " + low ); Compare the operations of these two search algorithms by answering the following questions. (You will probably find that it helps to use pencil and paper as you single-step carefully through the code with a view to counting the number of iterations.) If array contains 10 elements and there is just one occurrence (at index 0) of target as an element of array, how many iterations does the sequential search the binary search require in order to find target? If array contains 10 elements and there is just one occurrence (at index 9) of target as an element of array, how many iterations does the sequential search the binary search require in order to find target? If array contains 10 elements and target is not one of them, how many iterations does it take the sequential search the binary search to discover this fact? (i) 1 (ii) 3 (i) 10 (ii) 4 (i) 10 (ii) at most 4 (It depends how big target is in relation to the elements of array. If all the elements are less than target, then 4 iterations will be required; if all the elements are greater than target then 3 iterations will be required. Otherwise 4 iterations will be required.)

Binary Comparison in Insertion Sorting

Sorting an array in place has the advantage that no additional memory is consumed in the creation of a destination array. If the source array is very large, this may be a significant factor. On the other hand, there can be advantages to creating a destination array. For example, you may want to keep a copy of the unsorted array. Alternatively, if memory is not a problem but efficiency of performance may be, then you might use a destination structure — such as an ArrayList — that provides an efficient method of inserting an object. It is interesting to note that, in our description, an insertion sort uses a sequential search (from right to left) to find the proper location for the next element. This sequential search is conducted on an array that is sorted (or, in the in-place case, on an array whose initial segment is sorted). It is therefore possible to use a binary search as we look for the proper location of the next element; such a sort is called a binary insertion sort. By employing a binary insertion sort algorithm, many fewer comparisons may be required, but we may not gain the full benefit of this saving unless we use a destination structure that allows efficient insertions. A common variation of the insertion sort uses the break keyword. Let us demonstrate: public class MainClass { public static void insertionSort( int[] a ) { int i, k, t; for ( k = 2 ; k <= a.length ; k++ ) { t = a[ k - 1 ]; for ( i = k - 1 ; i > 0 ; i-- ) { if ( a[ i - 1 ] <= t ) break; else a[ i ] = a[ i - 1 ]; } a[ i ] = t; } } public static void main( String[] args ) { int[] a = { 4, 2, 3, 9, 7, 8, 0, 1, 6, 5 }; insertionSort( a ); for ( int i : a ) System.out.print( i + " " ); } } 0 1 2 3 4 5 6 7 8 9 Among other uses, the break keyword causes the currently executing loop to exit, with execution continuing at the first statement that follows the loop. Although the break keyword is not part of the Advanced Placement Computer Science Java subset, it is valuable for you to see an example of its use. In the above implementation of insertion sort, notice in particular how the current value of i is used to make the insertion. (What is the value of i if the loop exits normally?)

Stuff with strings

Strings are objects. Use equals() method to take the one parameter (in this case a string) and return a boolean value that can only be true or false. Cannot use relational operators because different storage areas. (SHOULD PROBABLY REVIEW THAT)

THE JAVA SUBSET

The Java Subset The Development Committee has defined a restricted subset of Java to be tested on the exam. The purpose of the subset is to focus the AP CS program more on general concepts than on the specifics of Java and to limit the scope, especially of material related to the peculiarities of Java. The subset is described in The College Board's Computer Science A Course Description; we have a link to it from this course's web site www.skylit.com/beprepared/. What is in the subset? Actually, quite a bit. Comments: /* ... */, //, and /**...*/, @param and @return tags. boolean, int, and double primitive data types. (int) and (double) casts. Other primitive data types, including char, are not in the subset and should be avoided on the exam. Assignment (=), arithmetic (+, -, *, /, %), increment/decrement (++, --), compound assignment (+=, -=, *=, /=, %=), relational (<, >, <=, >=, ==, !=), and logical (&&, ||, !) operators. Use only the postfix form of ++ and -- (k++ or k--), and do not use them in expressions. + and += operators for concatenating strings. String's compareTo, equals, length, substring, and indexOf(String s) methods. \n, \\, and \" escape sequences in literal strings. System.out.print and System.out.println. One- and two-dimensional arrays, array.length, arrays of objects, initialized arrays such as int x[] = {1,2,3}; if-else, for, including the "for each" form, for (type x : values) ..., while, return. But do-while and switch are not included. Classes. Constructors, the new operator, public and private methods, static methods, static variables and static final variables (constants), overloaded methods, null. All instance variables are private. Default initialization rules are not in the subset and won't come up on the exam. Inheritance, interfaces and abstract classes, extends, implements. Calling a superclass's constructor from a subclass (as in super(...)). Calling a superclass's method from a subclass (as in super.someMethod(...)). Passing this object to a method (as in otherObject.someMethod(this)). NullPointerException, IndexOutOfBoundsException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException. Library classes, methods, and constants: Object: equals(Object other), toString() String: length(), substring(...), indexOf(String s) Integer: Integer(int x), intValue(); Integer.MIN_VALUE and Integer.MAX_VALUE. Double: Double(double x), doubleValue() Math: abs(int x), abs(double x), pow(double base, double exp), sqrt(double x), random() Also understand toString methods for all objects, the equals and compareTo methods for String, Integer, and Double. Comparable<T> interface is not in the subset, but is worth knowing. The List<E> interface and the ArrayList<E> class (see Section 2.6).

About quadratic time

The selection and insertion sort algorithms are called quadratic sorts and are said to execute in quadratic time because, if an array A2 is c times as long as an array A1 (where c is some positive number), then each of these sorting algorithms requires roughly c2 times as many comparisons to sort A2 as it does to sort A1. In particular, if A2 is 100 times as long as A1, then it will take a quadratic sort about 10,000 times as long to sort A2 as it will to sort A1. In general, any process that involves an inner loop inside an outer loop, where both loops perform a number of iterations that is controlled by the value of the same variable, n, will run in quadratic time. For example, the execution time of this code: int n = <some integer>; int i, j; for ( i = 0 ; i < n ; i++ ) { for ( j = 0 ; j < n ; j++ ) { // code not shown } } will be close to some fixed number of milliseconds multiplied by the square of the value of n. In contrast, a process that involves a single loop like this: int n = <some integer>; int i; for ( i = 0 ; i < n ; i++ ) { // code not shown } is said to run in linear time since the execution time will be close to some fixed number of milliseconds multiplied by the value of n. This is the case with an insertion sort when the source array is already sorted (or very nearly so). For such an array, an insertion sort requires roughly the same number of comparisons as there are elements in the array. Therefore, in the best case, an insertion sort runs in linear time.

Polymorphism (a bit more)

The technique of treating an object as though it were an instance of a superclass of its true class is called polymorphism

THE PRINTTF CLASS BOOM

These three examples indicate the typical syntax of a printf() statement: a String literal to be printed (e,g., "City: " , "Zip Code: ", and "pi: ") a format specifier (%-15s%n , %10d%n, %10.4f%n) a variable to be printed (e.g., cityName, zipCode, pi)

Programming control structures

Three basic programming control structures: Sequential-simple Conditional-ifs Iterative-loops-fors and whiles

Concatenation

an operation that combines two arguments into one ex. two strings in a print statement

Each of the following pairs of methods work in concert, to read in a stream of String data from a text file. Study the excerpts from the Scanner class API to gain an overview of how each of these methods performs.

boolean hasNext() returns true if this scanner has another token in its input String next() Finds and returns the next complete token from this scanner boolean hasNextLine() returns true is there is another line in the input of this scanner String nextLine() Advances this scanner past the current line and returns the input that was skipped. The boolean methods hasNext() and hasNextLine() are used in the while loop condition to determine when the loop should terminate. (either one depending on the text file organization) hasNext() deals with individual tokens determined by white space, whereas the hasNextLine() method deals with entire lines of tokens separated by a carriage return (basically a new line) As long as there are more tokes to read from the file, these methods will be evaluated as true and more information will be read by the next() and nextLine() methods, respectively. EOF is used the the boolean methods

Search Sorting Algorithm

int[] array = { 12, 14, 15, 11, 13 }; int i, k, posmax; for ( i = 4 ; i >= 0 ; i-- ) { posmax = 0; for ( k = 0 ; k <= i ; k++ ) { if ( array[ k ] > array[ posmax ] ) posmax = k; } int temp = array[ i ]; array[ i ] = array[ posmax ]; array[ posmax ] = temp; }

Declaring an array

int[number of elements or elements themselves ] myArray; *I added spaces in between the brackets so it was easier to tell that they were brackets int a[ number of elements or elements themselves]; ________ ** myArray = new int[ 10 ]; myArray[ 0 ] = 5; myArray[ 1 ] = 0; myArray[ 2 ] = 5400; myArray[ 4 ] = -96725; double[] d = new double[ 100 ];

Each of the following pairs of methods work in concert, to read in a stream of int or double data from a text file. Study the excerpts from the Scanner class API to gain an overview of how each of these methods performs.

more Scanner class methods!! AHHH boolean hasNextInt() returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. int nextInt() Scans the next token of the input as int boolean hasNextDoule() returns true if the next token in this scanner's input can be interpreted as a double value suign the nextDouble() method double nextDouble() Scans the next token of the input as a double

String literal

one or more characters enclosed in double quotation marks

A program in Bluejay is called a

project


Set pelajaran terkait

AP Psych Unit 7 Key Contributors

View Set

ExamFx Chapter 13 Commercial General Liability

View Set

Bio 8 - Chapter 16: The Cell Cycle

View Set

Russia 1894-1941 - Rule of Tsar Nicholas II

View Set

chapter 16: lymphatic & immunity

View Set

"First Aid- Chapter 18: Substance Abuse and Misuse

View Set

CHapters 5-7 Developmental Psyche

View Set