ITSC 2214 Test 1 Chapters 1-3
O(N^2)
Quadratic Example: SelectionSort(int numbers, N) { for (i = 0; i < numbersSize; ++i) { indexSmallest = i for (j = i + 1; j < numbersSize; ++j) { if (numbers[j] < numbers[indexSmallest]) { indexSmallest = j } } temp = numbers[i] numbers[i] = numbers[indexSmallest] numbers[indexSmallest] = temp }
Integer.toBinaryString(someInteger)
Returns a String containing the binary representation of someInteger. someInteger may be an Integer object, a int variable, or an integer literal. This static method is also available for the Long classes (e.g., Long.toBinaryString(someLong)). Integer.toBinaryString(num1) // Returns "1010" Integer.toBinaryString(regularInt) // Returns "10100" Integer.toBinaryString(7) // Return "111"
intVar.toString()
Returns a String containing the decimal representation of the value contained by the primitive wrapper object. num1.toString() // Returns "10" num2.toString() // Returns "3.14"
Integer.toString(someInteger)
Returns a String containing the decimal representation of the value of someInteger. someInteger may be an Integer object, a int variable, or an integer literal. This static method is also available for the other primitive wrapper classes (e.g., Double.toString(someDouble)). Integer.toString(num1) // Returns "10" Integer.toString(regularInt) // Returns "20" Integer.toString(3) // Returns "3"
Pop(stack)
Returns and removes item at top of stack > Ex. Pop(stack) returns: 99. Stack: 77
Peek(stack)
Returns but does not remove item at top of stack > Ex. Peek(stack) returns 99. Stack still: 99, 77
GetLength(stack)
Returns the number of items in the stack > Ex. GetLength(stack) returns 2
IsEmpty(stack)
Returns true if stack has no items > Ex. IsEmpty(stack) returns false
array indexes start at ___
0
ArrayList<Integer> itemsList = new ArrayList<Integer>(); itemsList.set(0, 99) What is the size?
0 / Error > The ArrayList has no elements yet, so trying to access element 0 yields an error.
a class can inherit from ___ superclass(es)
1
For an list that maintains elements in ascending order, the program performs the follow steps:
1. Find the index of the first existing element that is greater than the element being added. 2. Add the new element at that index.
Given a function that describes the running time of an algorithm, the Big O notation for that function can be determined using the following rules:
1. If f(x) is a sum of several terms, the highest order term (the one with the fastest growth rate) is kept and others are discarded. 2. If f(x) has a term that is a product of several factors, all constants (those that are not in terms of x) are omitted.
what relational operators can compare primitive wrapper class objects?
<, <=, >, and >=
what relational operators can't compare primitive wrapper class objects?
== and != > they check the reference itself, not the value it references, so it'll be FALSE unless they refer to the exact same object > CAN compare primitive wrapper classes and primitive variables and literal constants
The ArrayList class, like many other data structures, uses generics to allow it to store various data types. Which of the following statements are true regarding class level generics? Select all that apply.
> A class can have multiple type variables, which can be either bounded or unbounded > A class can have fields of the generic types used
Suppose you are asked to write an implementation for a method called removePositives(). This method should take in an array list containing Integer objects as a parameter, and remove all the positive numbers from the list. Before writing this method, you want to write a set of test cases for it. Select all of the following test scenarios that should be included in order to provide thorough coverage of likely errors:
> A list with only non-positive numbers > A list with only positive numbers > A list containing at least one zero > A list with a positive number at the beginning > An empty list > A list with a positive number at the end
Features of a good testbench include:
> Automatic checks > Independent test cases > 100% code coverage > Includes not just typical values but also border cases
Suppose you were about to write a method called encrypt(), that will take a string as a parameter and return an "encrypted" version of the string. For now, we will use a really simple encryption strategy based on this pseudo-code: int pos = word.length() / 2; result = encrypt( word.substring( pos ) ) + encrypt( word.substring( 0, pos ) ); Before we write the code, however, we want to create a set of tests that will thoroughly exercise this method. One test case might be: assertEquals( "TERCES", encrypt( "SECRET" ) ); Select all of the additional test cases, if any, you would also need to write in order to check the behavior of encrypt():
> Check that encrypt(null) behaves properly > Check that encrypt("A") returns "A" > Check that encrypt("HAPPY") returns "YPPAH" > Check that encrypt("") returns ""
@see
> For all > Used to refer reader to relevant websites or class members
@version
> For classes > Used to specify a version number
@author
> For classes > Used to specify an author
@return
> For methods > Used to describe the value or object returned by the method
@param
> For methods, constructors > Used to describe a parameter
Any class that implements an interface must:
> List the interface name after the keyword implements > Override and implement the interface's methods
Consider the following method definition: public void removeNegatives( ArrayList list ) { int i = 0; int n = list.size(); while ( i < n ) { Integer x = (Integer)list.get( i ); if ( x.intValue() < 0 ) { list.remove( i ); n--; } i++; } } Select all of the following test scenarios that will reveal incorrect behavior in this method:
> Pass in a list containing {1, -2, -3, 4, 5}, and assert that afterward, this list contains {1, 4, 5} > Pass in a list containing {-1, -2, -3, -4, -5}, and assert that afterward, this list is empty
A JUnit test is aimed at testing what?
> Whether state variables are properly maintained while a method does what it is supposed to. > Whether a method performs the function it is supposed to.
enhanced for loop / for each loop
> a for loop that iterates through each element in an array or Collection > declares a new variable that will be assigned with each successive element of a container object, such as an array or ArrayList > The enhanced for loop only allows elements to be accessed forward from the first element to the last element
Information hiding / encapsulation
> a key ADT aspect wherein the internal implementation of an ADT's data and operations are hidden from the ADT user > allows an ADT user to be more productive by focusing on higher-level concepts > allows an ADT developer to improve or modify the internal implementation without requiring changes to programs using the ADT
reference variable
> a variable that points to, or refers to, an object or array > stores a reference, or the memory location, of the object to which it refers
checked exception
> an exception that a programmer should be able to anticipate and appropriately handle > include Exception and several of its subclasses
catch
> clause which immediately follows a try block > if the catch was reached due to an exception thrown of the catch clause's parameter type, the clause executes > The clause is said to catch the thrown exception > also called a handler
A catch block is called a ___ because ___
> handler > it handles an exception
the user of an object need only know the object's ___ and not the object's ___
> interface > implementation
Perfect size arrays have two advantages over oversize arrays:
> methods that use perfect size arrays have fewer parameters than methods that use oversize arrays > a perfect size array contains no excess elements
A class can implement ___ interfaces using a ___
> multiple > comma separated list
FileReader
> provides an input stream that allows a programmer to read characters from the file specified via FileReader's constructor. > supports several overloaded read() methods for reading characters and a close() method for terminating the stream and closing the file.
passing a primitive wrapper class passes by ___ whereas passing a primitive type passes by ___
> reference > value
throw
> statement that appears within a try block; if reached, execution jumps immediately to the end of the try block > The code is written so only error situations lead to reaching a throw > The throw statement provides an object of type Throwable, such as an object of type Exception or its subclasses > The statement is said to throw an exception of the particular type > A throw statement's syntax is similar to a return statement
oversize arrays typically use three variables including:
> the array reference > the current size > a constant for the array capacity
The ArrayList type is an ___
ADT implemented as a class
A class that provides default code to other classes that use that class
Abstract class > Only abstract classes can provide code to the subclasses. Interfaces provide method declarations but no code implementing methods.
A class that provides default variables.
Abstract class > Only abstract classes can provide variables/fields to the subclasses.
A programmer needs to write a program that keeps track of the amount of time worked on a large project by storing the number of hours the programmer worked every day in an array. Which type of array is best?
Although choosing the number of array elements needed for the entire project may be challenging, an oversize array is best because the array will only have to be constructed once.
char associated primitive type
Character
initialize an object of a generic class code:
ClassName<ArgumentType> objectName = new ClassName<ArgumentType>(parameters); > ArgumentType is the type you want to send into the generic class > can't use primitives as ArgumentType, you need to use wrapper classes
declare and initialize array code:
ClassName[] arrayName = new ClassName[size];
O(c^N)
Exponential Example: Fibonacci(N) { if ((1 == N) || (2 == N)) { return 1 } return Fibonacci(N-1) + Fibonacci(N-2) }
If the function representation doesn't have an N, then the Big O notation will be ___
O(1)
Which of the following choices demonstrates increasing levels of complexity in Big O notation?
O(1) --> O(logN) --> O(N) --> O(NlogN) --> O(N^2)
What is the big-O notation for the worst-case runtime? negCount = 0; for(i = 0; i < N; ++i) { if (numbers[i] < 0 ) { ++negCount; } }
O(N) The total number of operations include: 1 operation before the loop, 1 operation at the start of the loop, 4 operations that execute each of the N loop iterations, and 1 operation for the final loop condition check. f(N) = 4*N+3 O(4*N+3) = O(N)
Integer.valueOf(someString)
Parses someString and returns a new Integer object with the value encoded by someString. This static method is also available for the other primitive wrapper classes (e.g., Double.valueOf(someString)), returning a new object of the corresponding type. Integer.valueOf(str1) // Returns Integer object with value 32 Integer.valueOf("2001") // Returns Integer object with value 2001
Integer.parseInt(someString)
Parses someString and returns an int representing the value encoded by someString. This static method is also available for the other primitive wrapper classes (e.g., Double.parseDouble(someString)), returning the corresponding primitive type. Integer.parseInt(str1) // Returns int value 32 Integer.parseInt("2001") // Returns int value 2001
object-initialization-style wrapper declaration code:
PrimitiveWrapper varName = new PrimitiveWrapper(primitive value);
maximum value code:
PrimitiveWrapper.MAX_VALUE
minimum value code:
PrimitiveWrapper.MIN_VALUE
Which method call would add "Raven" to a perfect size array?
The addElement method constructs a new array, adds "Raven" to the end, and returns the reference. perfectSizeArray is assigned with the reference to the new array.
Which method call would add "Raven" to an oversize array?
The method call uses both the array reference and size and stores the returned size.
Regression testing means to check if a change to an item caused previously-passed test cases to fail. (T/F)
True Even minor changes to an item may unexpectedly introduce bugs. An automated testbench can easily be run when an item is changed, to detect such "regression".
A method cannot be used to swap two references (T/F)
True References are stored in the stack frame. The references can be swapped within a stack frame. However, stack frames are deleted when a method returns, leaving the original references unchanged.
If excptType2 inherits from excptType1, then the inclusion of the second catch block (i.e., catch (excptType2 excptObj)) below the first catch block results in a compiler error as the second catch block would never be executed. (T/F)
True The catch blocks are checked in sequence from top to bottom for a match. Because excptType2 inherits from excptType1, the first catch block will always be the only block executed whenever objOfExcptType2 is thrown. In this case, the compiler will report an error.
The original parameter in the Arrays class' int[] copyOfRange(int[] original, int fromIndex, int toIndex) method could be used for either a perfect size or oversize array (T/F)
True While this method was designed for oversize arrays, the method can also be used for perfect size arrays since fromIndex could be 0 and toIndex could be the array's length.
After itemList.clear(), itemList.get(0) is an invalid access? (T/F)
True clear() removes all elements. So no element 0 exists.
Don't forget to review ___
UML rules from ITSC 1213
In an ArrayStack, pushing and popping items have the same big O complexity and are essentially just inverse operations of each other. What is the main difference in the algorithms besides that one adds and one removes, and what is its effect on the Big O complexity?
When pushing an item on the ArrayStack, the array may need to be expanded. This technically makes the operation O(N), but because this is not frequently needed, it is considered amortized and pushing is still qualified as O(1).
Linked list: Stores ___
each item anywhere in memory, with each item referring to the next item in the list. Supports fast inserts or removes, but access to i'th element may be slow as the list must be traversed from the first item to the i'th item. Also uses more memory due to storing a link for each item.
element
each item in an ArrayList
test vector
each unique set of input values
if there is a throws clause in a method, then ___
either the clause must be enclosed in a try catch construct or the method header has to specify throws
A new memory allocation occurs
every time a new value is assigned to an Integer variable, and the previous memory location to which the variable referred, remains unmodified
Which function best represents the number of operations in the worst-case? i = 0; sum = 0; while (i < N) { sum = sum + numbers[i]; ++i; }
f(N) = 3N + 3 2 operations execute before the loop. The loop condition and 2 operations in the loop executes N times, yielding 3N operations. The loop condition is checked 1 additional time before the loop terminating. The total operations as a function of N can be expressed as 2 + 3N + 1, or 3N + 3.
FileReader example code:
fileCharStream = new FileReader(fileName); charRead = fileCharStream.read() > outputs -1 when the end of the file has been reached fileCharStream.close();
constant declaration code:
final int objectName;
a try block must be ___
followed by a catch or finally block no matter what
create for each loop code:
for (Type item : arrayListName){} > dont use regular arrays
If you have studied branches, you may recognize that each print statement in main() could be replaced by an if statement like ___
if ( hrMinToMin(0, 0) != 0 ) { System.out.println("0:0, expecting 0, got: " + hrMinToMin(0, 0)); } "but the assert is more compact" haha yeah but the challenge question for 2.3 is on this instead of assert so jokes on you
nested loop Big O notation
if you have an N loop nested in an N loop then the Big O notation will be N^2, same applies to other exponents as well
An array is stored ___
indirectly in the heap, and only the reference to the array is stored in the stack frame > # of memory addresses equal to array length + 1 are reserved in the heap for the array's values
creating an array of object references does not ___
initialize the objects for you, but it does declare them
What assert calls do you need to test that a pop operation works on a stack of Integers? Result is what you get from the pop operation, expResult is what you think you should get, and instance is the stack. Assume you have created the instance, but done nothing else.
instance.add(7);
Method that determines the number of times a given value occurs in an oversize array:
int frequency(int[] arrayReference, int arraySize, int target)
generic type method header code:
public <GenericType> ReturnType methodName(parameters) { } > the type/template is the ParamType, and is the type of the generic class
type bound generic
public <ParamType extends BoundType> ReturnType methodName(parameters) { } > the type bound is the BoundType and limits the class types for which a type parameter is valid to BoundType or something that implements/inherits it
limiting generic methods to things that are comparable code:
public <ParamType extends Comparable<ParamType>> ReturnType methodName(parameters) { }
Method definition with multiple generics code:
public <ParamType1 extends Comparable<ParamType1>, ParamType2> ReturnType methodName(parameters) { }
to create a generic class:
public class ClassName <ParamType> { } > works the same as generic methods, including the type bounds and necessity of wrapper classes
create interface code:
public interface ClassName {}
throws clause method header code example:
public static int getHeight() throws Exception {}
Arrays are passed by ___
reference
Collection
represents a generic group of objects known as elements
double, boolean, long associated primitive type
same thing but the first letter is capitalized
Javadoc ___ incorrectly placed doc comments.
silently ignores
Before finding Big O runtime complexity ___
simplify/reduce the target function
Doc comments
specially formatted comments for Javadoc which are multi-line comments consisting of all text enclosed between the /** and */ characters
interfaces
specifies a set of methods that an implementing class must override and define
different methods store values in different ___
stack frames
push
stack operation that inserts an item on the top of the stack
pop
stack operation that removes and returns the item that is at the top of the stack
finding Big O for composite functions:
take away whatever O is in the function, combine like terms then multiply the entire function by O and use the two Big O rules
border cases
test cases which represent fringe scenarios > Ex. border cases for the above method might include inputs 0 and 0, inputs 0 and a huge number like 9999999 (and vice-versa), two huge numbers, a negative number, two negative numbers, etc
A disadvantage of using perfect size arrays is ___
that if the number of array elements needs to change, a new array will have to be constructed
Unit testing
the process of individually testing a small part or unit of a program, typically a method
Array initialization can only occur when ___
the reference is declared
worst-case runtime
the runtime complexity for an input that results in the longest execution
Perfect sized arrays are used when ___
the size of the array is fixed by the context of the program
last-in first-out
the type of ADT that a stack is
if an operation runs every other loop ___
then its function representation is N/2, this also applies to a function that runs every third (N/3) or fourth(N/4) time
If an exception is thrown within a method and not caught within that method ___
then the method is immediately exited and the calling method is checked for a handler, and so on up the method call hierarchy
Unit test
to create and run a testbench for a specific item (or "unit") like a method or a class
A common error is to not return ___
to not return the new size of an oversize array that was modified in a method
Regression testing
to retest an item like a class anytime that item is changed; if previously-passed test cases fail, the item has "regressed"
try throw catch finally example code:
try { throw new Exception("Whoops"); } catch (Exception except) { System.out.println(except); } finally { System.out.println("Finishing up) }
exception-handling constructs
try, throw, and catch, keep error-checking code separate and to reduce redundant checks
A method that expects an oversize array as an argument will have:
two parameters to pass the array: one for the array reference and one for the array size. > Ex: int binarySearch(String[] arrayReference, int arraySize, String searchKey)
A programmer is not required to handle ___
unchecked exceptions or even specify that a method may throw them
when using for each with arraylists, dont forget to:
use classes for primitive types
primitive data types are passed by ___
value
Which method signature is best for sorting an oversize array?:
void sort(int[] arrayRef, int fromIndex, int toIndex) > This method signature allows oversize arrays to be sorted, and also allows any part of an array to be sorted. The parameters fromIndex and toIndex make the method more useful.
Method that sorts the elements in an oversize array:
void sortOversizeArray(int[] arrayReference, int arraySize) > The method signature has parameters for the array reference and current array size. As sort does not change the number of elements, the method's return type is void.
Creating a program may start by a programmer deciding ___
what "things" exist, and what each thing contains and does
documentation
which is a written description of a program and its various parts, intended to be read by programmers who must maintain or interface with the program
A programmer should also utilize exception handling when ___
writing to file output streams in order to handle exceptions resulting from invalid or interrupted file operations, as shown below
finally
a block that follows all catch blocks when implemented, and always executes after the program exits the corresponding try or catch blocks regardless of exceptions thrown
IOException
a built-in checked exception inheriting from the Exception class thrown by most methods of the FileReader class > involved with reading or closing files
FileNotFoundException,
a built-in checked exception inheriting from the IOException class thrown by the constructors of the FileReader class > involved with opening files for reading
exception
a circumstance that a program was not designed to handle, such as if the user enters a negative height
generic class
a class definition having a special type parameter that may be used in place of types in the class
Attempting to invoke a class member via a generic type without specifying the appropriate type bound results in ___
a compiler error
abstract data type (ADT)
a data type whose creation and update are constrained to specific well-defined operations
linked list
a list wherein each item contains not just data but also a reference — a link — to the next item in the list
Big O notation
a mathematical way of describing how a function (running time of an algorithm) generally behaves in relation to the input size.
generic method
a method definition having a special type parameter that may be used in place of types in the method
perfect size arrays do not use ___
a number for declaring the array size when being declared/initialized
If a method returns an array reference, the method constructs:
a perfect size array > A oversize array cannot be constructed inside a method because the method would need to return both an array reference and array size, which is not permitted in Java
programmer can often pass:
a perfect size array to a method expecting an oversize array. > Ex: For the method int search(String[] arrayReference, int fromIndex, int toIndex, String target), a programmer can pass a perfect sized array by passing 0 to fromIndex and passing the array's length field to toIndex, such as: foundIndex = search(carsNames, 0, studentName.length, "VW");
testbench
a program whose job is to thoroughly test another program (or portion) via a series of input/output checks known as test cases
immutable
a programmer cannot change the object via methods or variable assignments after object creation ex. jerseyNumber = 24; does not change the value in jerseyNumber's object. Instead, the assignment allocates a new Integer object with value 24, returns a reference to that new object, and assigns the reference to variable jerseyNumber. jerseyNumber refers to the new Integer object, and the original Integer object is unchanged.
immutable
a programmer cannot modify the object's contents after initialization; new objects must be created instead > Ex. primitive wrapper classes, such as Integer and Double, and the String class
If a method throws an exception not handled within the method ___
a programmer must include a throws clause within the method declaration, by appending throws Exception before the opening curly brace
testbench/test harness
a separate program whose sole purpose is to check that a method returns correct output values for a variety of input values
test cases
a series of input/output checks
Javadoc
a tool that parses source code along with specially formatted comments to generate documentation
Push(stack, x)
Inserts x on top of stack > Ex. Push(stack, 44). Stack: 44, 99, 77
int associated primitive type
Integer
A class that provides an API that must be implemented and no other code.
Interface > An interface does not restrict future inheritance, so is the best choice if no other code is provided.
A class that provides only static final fields.
Interface > Interfaces can declare public static final fields and don't restrict a class' inheritance.
primitive wrapper classes
built-in reference types that augment the primitive types ex. Integer class
reference type
can refer to an instance of a class, also known as an object
For Java's built in stack, what method would you use to check how many elements a stack can hold?
capacity()
A programmer must ensure that files are ___
closed when no longer in use, to allow the JVM to clean up any resources associated with the file streams
Error-checking code
code a programmer writes to detect and handle errors that occur during program execution
Java Collection Framework
defines interfaces and classes for common ADTs known as collections in Java
An int and double variable is stored ___
directly in the stack frame
primitive type
directly stores the data for that variable type, such as int, double, or char
API (application programming interface)
documentation generated by Javadoc
FileWriter
provides overloaded write() methods to write a stream of characters and a close() method to flush the underlying buffer and close the stream > constructor throws IOException
declare and initialize ArrayList code:
ArrayList<ClassName> arrayListName = new ArrayList<ClassName>();
O(1)
Constant Example: FindMin(x, y) { if (x < y) { return x } else { return y } }
Programmers optionally may explicitly specify the generic type as a special argument, as in:
ItemMinimum.<Integer>tripleMin(num1, num2, num3);
What happens after the statement below? vowels = {'a', 'e', 'i', 'o', 'u', 'y'};
Error > Array initialization can only be done when the array reference is declared, so initializing the array vowels a second time results in an compilation error.
ArithmeticException
Indicates the occurrence of an exceptional arithmetic condition (e.g., integer division by zero).
A stack is an appropriate data structure to use when you want to process items in the order in which they are received.
False
Assuming itemList is 99 33 55 77 44, then itemList.remove(55) results in: 99 33 77 44 (T/F)
False > The argument to remove() is the position (or object reference) to be erased. To erase 55, the position argument should have been 2.
A key advantage of javadoc comments is that a change to a comment in the java source automatically updates documentation on an HTML webpage. (T/F)
False > The javadoc tool must be run to create new HTML.
The value of an Integer passed to a method can be modified within the method. (T/F)
False An Integer object is immutable, meaning the value cannot be modified after the object is created. Assignment to an Integer parameter within a method creates a new Integer object and assigns the new object's reference to the parameter.
Unit testing means to modify method inputs in small steps known as units. (T/F)
False yeah but its actually True though and heres why So the idiotic attempt at justification from zybooks stays "Unit refers to a part of a program, typically a method (the actual definition of unit testing says "testing a small part or unit of a program, typically a method"). Unit testing means to test just that part(unit testing is defined as "individually testing a small part"), separately from other program parts." Oh and unit testing does "modify method inputs" as well since a test harness used in unit testing "checks that a method returns correct output values for a variety of input values" so yeah this answer is True
ArrayList add/remove performance problem
For ArrayLists with thousands of elements, a single call to add() or remove() can require thousands of instructions, so if a program does many insert or remove operations on large ArrayLists, the program may run very slowly
Given the following definition of the InfoRandomizer class, create an InfoRandomizer object of type String called myRandomizer, with parameters so that item1 holds a string that says "hello" and item2 holds a string that says "bye". public class InfoRandomizer <T extends Comparable<T>>{ private T item1; private T item2; public InfoRandomizer(T i1, T i2){ item1 = i1; item2 = i2; } }
InfoRandomizer myRandomizer=new InfoRandomizer("hello", "bye");
Most FileReader methods and constructors throw exceptions of type ___
IOException > input/output exception
NullPointerException
Indicates a null reference.
ClassCastException
Indicates an invalid attempt to cast an object to type of which the object is not an instance (e.g., casting a Double to a String).
IndexOutOfBoundsException
Indicates that an index (e.g., an index for an array) is outside the appropriate range.
IOError
Indicates the failure of an I/O operation.
O(N)
Linear Example: LinearSearch(numbers, N, key) { for (i = 0; i < N; ++i) { if (numbers[i] == key) { return i } } return -1 // not found }
O(N log N)
Log-linear Example: MergeSort(numbers, i, k) { j = 0 if (i < k) { j = (i + k) / 2 // Find midpoint MergeSort(numbers, i, j) // Sort left part MergeSort(numbers, j + 1, k) // Sort right part Merge(numbers, i, j, k) // Merge parts } }
O(log N)
Logarithmic Example: BinarySearch(numbers, N, key) { mid = 0; low = 0; high = 0; high = N - 1; while (high >= low) { mid = (high + low) / 2 if (numbers[mid] < key) { low = mid + 1 } else if (numbers[mid] > key) { high = mid - 1 } else { return mid } } return -1 // not found }
**** you
Mohammed,Kaleel,Virendra
Which code will create a stack that can hold Strings called studentNames, and initialize its size to 50. Select all that are correct.
Stack studentNames = new Stack(50); Stack studentNames = new Stack< />(50);
A variable for a primitive wrapper class may be initialized when declared without using the new operator, similar to ___
Strings > Alternatively, the new operator can be used, as in Double distMiles = new Double(0.0); which is equivalent to Double distMiles = 0.0
When oversize arrays are passed to a method, two parameters are needed for:
both the array reference and the current size
The complexity of the algorithm below is O(1). for (i = 0; i < 24; ++i) { if (timeHour < 6) { tollSchedule[i] = 1.55; } else if (timeHour < 10) { tollSchedule[i] = 4.65; } else if (timeHour < 18) { tollSchedule[i] = 2.35; } else { tollSchedule[i] = 1.55; } } (T/F)
The statements within the for loop have a O(1) runtime. The for loop executes a constant number of times, so the for loop's runtime is 24 * O(1) = O(1). A loop with a constant number of iterations executes O(1) times.
Assume you already have an empty stack of Integers called nums1. What will the following code output? Stack<Integer> nums2 = new Stack<>(); nums1.push(56); nums1.push(77); nums1.push(93); nums2.push(nums1.pop()); nums2.push(nums1.pop()); System.out.println(nums2.peek());
This won't compile.
IllegalArgumentException
Thrown by a method to indicate an illegal or inappropriate argument.
The block tag specification below creates a reference to ElapsedTime's printTime() method. @see ElapsedTime#printTime() (T/F)
True > The @see block tag can be used to reference a method in another class by appending the class name and the # symbol before the method name, as in @see ElapsedTime#printTime()
A second catch block can never execute immediately after a first one executes. (T/F)
True Catch blocks are checked in sequence from top to bottom. The first that matches executes, after which execution jumps past the catch blocks, so a second one can't execute.
Type bounds are also necessary to enable ___
access to the class members of the class specified by the type bound (e.g., compareTo()) via a variable of a generic type > By bounding TheType to the Comparable interface, the programmer is able to invoke the Comparable interface's compareTo() method with the generic types
how to use generics in the method parameters:
after creating the generic statement just use the type parameter as the type for the parameter, when using multiple generics, specify which generic for each parameter
A testbench should be maintained ___
along with the item, to always be usable for regression testing
stack
an ADT in which items are only inserted on or removed from the top of a stack
perfect size array
an array where the number of elements is exactly equal to the memory allocated. > Ex: The maximum temperature for each day in the week could be stored in an array with 7 integer values. > int[] highTemps = {93, 80, 62, 75, 74, 89, 97}
oversize array
an array where the number of elements used is less than (or equal to???) the memory allocated > use counter to track number of elements > used when number of elements is uncertain or variable
subclass variable cannot hold ___
an object of its superclass.
ArrayList
an ordered list of reference type items, that comes with java
If a method returns an int, the method constructs:
an oversize array > the method must have an arraySize parameter and return an int, otherwise it could just be returning an int
Unchecked exceptions
are exceptions that result from hardware or logic errors that typically cannot be anticipated or handled appropriately, and instead should be eliminated from the program or at the very least should cause the program to terminate immediately > comprised of the Error and RuntimeException classes and their subclasses like NullPointerException, ArithmeticException, IndexOutOfBoundsException, and IOError
add item to arraylist code:
arrayListName.add(element) arrayListName.add(index, element) > when using index, item is added at the index and the existing item in that list are shifted into higher indexes
remove all elements from arraylist code:
arrayListName.clear()
return an element from an arraylist code:
arrayListName.get(index)
check if arraylist contains any elements code:
arrayListName.isEmpty() > Returns true if the ArrayList does not contain any elements. Otherwise, returns false.
remove element from arraylist code:
arrayListName.remove(index) & arrayListName.remove(existingElement) > when using index, items in higher indexes are shifted down to fill empty space
set item in an arraylist code:
arrayListName.set(index, element)
get size of an arraylist code:
arrayListName.size();
try
block that surrounds normal code, which is exited immediately if a throw statement executes
compare values of primitive wrapper class object code:
intVar.compareTo(otherIntVar); > return 0 if the two Integer values are equal, returns a negative number if intVar is less than otherIntVar's value, and returns a positive number if intVar is greater than otherIntVar's value. otherInteger may be an Integer object, int variable, or integer literal.
compare equality of primitive wrapper class object code:
intVar.equals(otherIntVar); > true if both Integers contain the same value. otherInteger may be an Integer object, int variable, or integer literal.
convert wrapper objects to primitive values code:
intVar.intValue(); doubleVar.doubleValue(); longVar.longValue(); charVar.charValue(); booleanVar.booleanValue();
ArrayList: Stores ___
items in contiguous memory locations. Supports quick access to i'th element via the set() and get() methods, but may be slow for inserts or removes on large ArrayLists due to necessary shifting of elements
to compile a java program with asserts you run ___
javac -ea HrMinToMinTestHarness.java
consider ___
leap years
What is the big-O notation for the worst-case runtime? nVal = N; steps = 0; while (nVal > 0) { nVal = nVal / 2; steps = steps + 1; }
nVal is decreased by half each iteration, so the loop will execute logN^2 times, and the Big O notation for that is O(logN)
Private class members are ___
not included by default in the API documentation generated by the Javadoc tool
when implementing multiple catch blocks, be sure to ___
not use a base class of an exception before its subclass, as it will catch exceptions before they ever reach the subclass
pulling a value from an undeclared array returns ___
null, regardless of type
List
one of the most commonly used Collection types as it represents an ordered group of elements -- i.e., a sequence
A method that expects a perfect size array as an argument will have:
one parameter for the array reference, but no parameter for the array size > Ex: int findIndexMax(String[] arrayReference)
Which type of array can be used? int removeAll(int[] arrayReference, int startIndex, int stopIndex, int target)
oversize or perfect size array > This method is designed to process a range within an array. By setting startIndex to 0 and stopIndex to the array's length or the array's size, the method can be used with oversize arrays. Because the method returns an int, a programmer can determine that the method could change the array size, so cannot be used with a perfect size array.
ArrayList does not support ___
primitive types like int
type arguments (stuff sent into the generic method) cannot be ___
primitive types such as int, char, and double > use wrapper classes instead
assert operator
prints an error message and exits the program if the provided test expression evaluates to false > Ex. assert expression: errormessage; > Ex 2. assert name.equals("Nathan") : "Assert name.equals("Nathan");
API documentation is meant to ___
provide a summary of all functionality available to external applications interfacing with the described classes