CS 163 Final

¡Supera tus tareas y exámenes ahora con Quizwiz!

Given the array: [1, 3, 5, 7, 9, 11, 13] Which index will a Linear Search for key 8 return?

-1

Recursive Binary Search

-Case 1: if the key is less than the middle element, recursively search the key in the first half of the array -Case 2: if the key is equal to the middle element, the search ends with a match -Case 3: if the key is greater than the middle element, recursively search the key in the second half of the array

Runtime Error

-Causes the program to abort -occurs while the program is running

wrapper class

-Primitive type capitalized & fully typed out -Use for array lists -use for toString -use to invoke methods to a char

Logic Error

-Produces incorrect result -bug in a program that causes it to operate incorrectly, but not to terminate abnormally (or crash)

linked list

-a self referential structure -advantage over arrays because no bound on capacity and can grow/shrink as needed (a dynamic structure) -basis for a lot of data structures -primary alternative to arrays

2D arrays

-an array of arrays (matrix) -initialization: type[ ][ ] arrName = new type[number of arrays][size of each array];

non-static

-belongs to an object of the class and you have to create an instance of the class to access it -can access any static method and any static variable without creating an instance of the class

class

-blueprint for an object -The data fields (instance variables) and methods within this define the behavior of the object -Constructors are used to create a new object -capitalized

switch statement

-checks some variable and executes code based on the case it falls into -Between cases, include break statements to prevent fall through (the execution of the same code for multiple cases) -have a default case which is executed in the event that none of the cases are matched

Linear Sort

-compares the key elements, key, sequentially with each elements in the array life -continues to do this until the key matches an element in the list or the list is exhausted without a match being found -if a match is made, it returns the index of the element in the array that matches the key -if no match is found, the search returns -1

arrays

-data structure that holds elements of the same data type. When an array is initialized, you must specify the size of your array and cannot be changed -declaration: dateType[ ] arrayName; -initialization: dataType[ ] variableName = new dataType[size];

instances of variables

-describe the state of the object -To access, you need an instance of the object that they describe

self-referential nodes

-each node object stores: one piece of integer data and a reference to another node -integerNode objects can be "linked" into chains to store a list of values

Binary Sort

-elements in the array must already be sorted -first compares the key with the element in the middle of the array -similar to searching a dictionary -if the key is equal to the middle element, the search ends with a match -if the key is less than the middle element, search in the first half of the array -if the key is great than the middle element, search in the second half of the array

Selection Sort

-find the minimal element in the array and put it in it's right location -finds the smallest number in the list and places its first -then finds the smallest number remaining and places it second, and so on until the list contains only a single number

Recursive Selection Sort

-find the smallest number in the list and swap it with the first number -the first number is in place, so sort the remaining shorter list recursively, until there is one element left

try/catch blocks

-handles exceptions -when trying to use a scanner on a file, it may not exist or can't be opened, which would throw a FileNotFoundException -put in: try { File file = new File("fileName.txt"); Scanner sc = new Scanner(file); } catch (Exception e) { System.out.println(e.getMessage()); }

recursion

-has a non-recursive base case and a recursive general case -alternative form of program -repetition without a loop

method

-help reduce redundant code and break down a task into smaller pieces -in this code: public static int rectangleArea(int length, int width) { int area = length * width; return area; } name is rectangleArea -to call, use its name and pass the required parameters -written in a class must be called using an object defined by that class unless the static keyword is used

boolean

-holds true or false value -primitive data type

interface

-list of methods that a class promises to implement. It can be thought of as a contract -only contains method stubs (there is no body of code)

static

-method that belongs to a class rather than an instance of a class -accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that member of a class

linked list interfaces

-object get(index) -index indexOf(object) -add(object) -add(index, object) -object remove(index) -object remove(object) -int size() -boolean isEmpty() -clear()

PrintWriter

-object used to write to a file -must close when finished

characteristics of recursion

-one or more base cases (the simplest case) are used to shop) are used to stop recursion -every recursive call reduced the original problem, bringing it increasingly closer to a base case until it becomes that case

short

-primitive data type -16-bit signed integer

float

-primitive data type -32-bit floating point number (number with a decimal point) -when doing operations, only one number needs to be this in order for the answer to be

int

-primitive data type -32-bit signed integer

double

-primitive data type -64-bit floating point number -when doing operations, only one number needs to be this in order for the answer to be

long

-primitive data type -64-bit signed integer

byte

-primitive data type -8-bit signed integer

char

-primitive data type -character -need ' ' around character when declaring

for loops

-run a segment of code a known number of times for (initial action; continuation condition; action after every iteration) { // do something }

while loops

-run a segment of code an unknown number of times while a condition is true while (condition) { // notice: no semicolon after condition // do something }

do-while loops

-run a segment of code at least once and then check if the condition is true do { // something } while (condition); // notice: semicolon after condition

substrings

-smaller string from a larger string -substring(int a) - create a substring starting at specified index through the end of the string -substring(int a, int b) - create a substring starting at specified index and and going up to (not through) the second index

precondition

-something that is guaranteed to be true before your method executes -do not need to check preconditions

postcondition

-something you are responsible for taking care of

indices

-start at 0, so a string with 10 characters will have an index starting at 0 and ending at 9 -0 based

printing a linked list

-start at the head of the list -while (there are more nodes to print) print the current node's item and go to the next node

Compile Error

-when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself

Order of Precedence (highest to lowest)

1) assignment = 2) comparison ==,!=,<,<=,>,>= 3) addition +, subtraction - 4) multiplication *, division / 5) parentheses ()

how many bits are in an "int"?

32

How many times does the print statement in the for loop execute? for(int i = 0; i < 347589; i++) System.out.print("I need Coffee!");

347,589

Consider the Java array declared and allocated by the statement below. What is the output of the System.out.println statement? double[][] dArray = new double[5][6]; System.out.println(dArray[1].length + "," + dArray.length);

6,5

Given the array: [1, 3, 5, 7, 9, 11, 13] When executing a Binary Search for key 3, what is the first element (not index) tested?

7

How many bits are in a byte?

8

What would the following method return when method1(4,5) is called? public static int method1(int i,int j) { return 4*i*j; }

80

For each comment in the for loop declaration below, indicate the type of statement that goes in that position. for (/*ONE*/;/*TWO*/;/*THREE*/)

ONE: Initial Action TWO: Loop continuation/condition THREE: action after each iteration

Consider: int pug = 10; int corgi = 2; while(corgi <= pug){ // loop 1 pug -= corgi; } System.out.println(pug); // question 2 for(int i = 10; i > 0; i -= 3){ // loop 2 System.out.println("It must be a hardware problem."); } int flower = 10; int bee = 2; do{ // loop 3 flower -= bee; }while(flower < bee == true); System.out.println(flower); // question 5 Question 1: How many times does loop 1 execute? Question 2: What is printed from the line marked question 2? Question 3: How many times does loop 2 execute? Question 4: How many times does loop 3 execute? Question 5: What is printed from the line marked question 5?

Question 1: Question 2: Question 3: Question 4: Question 5:

Is it a compile-time or run-time error when a Java program throws an exception because of an out of bounds array access?

Run-time

declaring scanner

Scanner sc = new Scanner(System.in);

Given the array: [5, 1, 3, 2, 7, 8, 0] Which of these shows the array after one pass of Selection Sort?

[0, 1, 3, 2, 7, 8, 5]

Given the array: [5, 1, 3, 2, 7, 8, 0] Which of these shows the array after one pass of Bubble Sort?

[1, 3, 2, 5, 7, 0, 8]

Which of the following options would declare an integer array named arr, but not initialize it? a) int[] arr; b) int arr; c) int arr=new int[]; d) int[] arr=new int[];

a

Consider: import java.util.ArrayList; public class ArrayListTest{ public static void main(String[] args){ ArrayList<Integer> intArray = new ArrayList<Integer>(); intArray.add(1); intArray.add(0); intArray.remove(0); intArray.add(2); System.out.println(intArray.size()); //Line 1 System.out.println(intArray.get(1)); //Line 2 System.out.println(intArray.indexOf(2)); //Line 3 System.out.println(intArray.contains(1)); //Line 4 intArray.clear(); System.out.println(intArray.size()); } } a) Line 1 prints... b) Line 2 prints... c) Line 3 prints... d) Line 4 prints...

a) b) c) d)

Consider: public class Grocer{ public void produce(){ Fruit apple = new Fruit; String s = apple.name; //Statement 1 int b = apple.barCode; //Statement 2 } } public class Fruit{ public String name; private int barCode; public static void main(String[] args){ Fruit plum = new Fruit; String s = plum.name; //Statement 3 int b = plum.barCode; //Statement 4 } } True/False: a) Statement 1 can access apple.name b) Statement 2 can access apple.barCode c) Statement 3 can access plum.name d) Statement 4 can access plum.barCode

a) b) c) d)

Given a class Square, for each of the following variable and method descriptions, select if that variable should be Static or Non-Static. a) length (The length of a side): b) count (The count of all squares created): c) String[] colors (A list of all possible colors that a Square can be): d) getColor() (Returns the color of the square):

a) b) c) d)

Consider: public class AnotherProgram { public void messenger(String message{ System.out.println(message); } public String iama(String name){ return "Hello, " + name + "."; } public int maths(){ System.out.print("A dozen dozen is "); return 144; } public boolean checker(boolean b){ return b; } public static void main(String[] args){ AnotherProgram ap = new AnotherProgram(); // First line System.out.println(ap.iama("monkey")); // Second Line messenger("It is " + ap.checker(true) + ", 'A' is a vowel."); // Third Line System.out.println(ap.maths() + "."); // Fourth Line System.out.println(ap.checker(false)); // Fifth Line ap.messenger("Have a great day!"); } } a) First line prints? b) Second line prints? c) Third line prints? d) Fourth line prints? e) Fifth line prints?

a) b) c) d) e)

Consider: public class Branching { public static void main(String[] args){ int i1 = 11, i2 = 6; char c0 = '$', c1 = 'e', c2 = 'x', c3 = '9'; boolean b0 = (i2 >= i1); if(b0) c3 = '5'; else c3 = '7'; i1--; switch (c3){ case '5': c0 = '#'; c1='q'; i1 = i1/2; break; case '7': c0 = '$'; c1='r'; i2 = i2/2; break; case '9': c0 = '%'; c1='s'; break; } System.out.println(b0); // Line 1 System.out.println(c0); // Line 2 System.out.println(c2); // Line 3 System.out.println(i2); // Line 4 System.out.println(i1); // Line 5 } } a) First line prints? b) Second line prints? c) Third line prints? d) Fourth line prints? e) Fifth line prints?

a) b) c) d) e)

Consider: public class Classes{ private int i = 0; public static int j = 4; public static Classes make(){ return new Classes(); } public int calculateResult(){ return i + j; } } a) Does this class have a default constructor? b) Does this class have a no-arg constructor? c) Does this class have instance data associated with it? d) Does this class have a getter method? e) Is there any way to change the value of i?

a) b) c) d) e)

Consider: public class SecondProgram{ pubic static void main (String[] args){ int anArray[]={3, 4, 5, 6, 7, 8, 9}; for (int i = 1; i < anArray.length;i++) anArray[ i ] = anArray[ i ]*2; // First line of output System.out.println(anArray.length*2); // Second line of output System.out.println(anArray[ 0 ]); // Third line of output System.out.println(anArray[ 2 ]); // Fourth line of output System.out.println(anArray[ anArray.length-1 ]); // Fifth line of output System.out.println(anArray[ 5 ]-2); } } a) First Line Output b) Second Line Output c) Third Line Output d) Fourth Line Output e) Fifth Line Output

a) b) c) d) e)

Consider: public class ThirdProgram { public static void init (String[][] sArray){ for (int row = 0; row < sArray.length; row++) for (int col = 0; col < sArray[ row ].length; col++)sArray[ row ][ col ] = row + ":" + col; } public static void main (String[] args){ String[][] strings2D = new String[ 2 ][ 3 ]; // First line of output System.out.println(strings2D.length); // Second line of output init(strings2D);System.out.println(strings2D[ 0 ].length); // Third line of output System.out.println(strings2D[ 1 ][ 2 ]); // Fourth line of output strings2D[ 0 ][ 1 ] = "Very";System.out.println((Arrays.toString(strings2D[ 0 ]))); // Fifth line of output strings2D[ 1 ][strings2D[ 0 ].length-1] = "Nice";System.out.println(Arrays.toString(strings2D[ 1 ])); } } a) First Line b) Second Line c) Third Line d) Fourth Line e) Fifth Line

a) b) c) d) e)

Consider: public class FileIO { public static void main(String[] args) { int i; double d; try { Scanner scan = new Scanner(new File("data.txt")); System.out.println(scan.nextLine()); char c0 = scan.next().charAt(0); char c1 = scan.next().charAt(0); System.out.println(c0 + "," + c1); System.out.println(scan.nextInt() + ":" + scan.nextDouble()); d = scan.nextDouble(); i = scan.nextInt(); System.out.printf("%0.1f, %d\n", d, i); scan.close(); } catch (Exception e) { System.out.println("Exception!"); } } } "data.txt" file: Computer ScienceJava Programming 123 567 12.34 4.32 a) First Line Output b) Second Line Output c) Third Line Output d) Fourth Line Output

a) b) c) d)

Consider: public class SecondProgram { public static void main(String[] args){ int i0 = 8, i1 = 5, i2 = 2; double d0 = 1.5, d1 = 4.2; // First line System.out.printf("%.1f\n", i0 * d0); // Second line System.out.println(i0 % i1 + i2 * i0); // Third line System.out.printf("%.2f\n", (i0 - 3.5) * i2); // Fourth line System.out.println(d1 <= 4.3); // Fifth line System.out.println((i0/i1)*i1 + (i0 % i1)); } } a) First line prints? b) Second line prints? c) Third line prints? d) Fourth line prints? e) Fifth line prints?

a) 12.0 b) 19 c) 9.00 d) true e) 8

Consider: public class Employee { private boolean salary = false; private int hours = 0; private int rate = 0; public Employee(int rate) { this(rate, 1); salary = true; } public Employee(int rate, int hours) { this.rate = rate; this.hours = hours; } public int payEmp() { return rate * hours; } public static void main(String[] args) { Employee bob = new Employee(5,5); Employee alice = new Employee(100); Employee linda = new Employee(6,6); Employee sam = new Employee(200); Employee[] employees = {bob, alice, linda, sam}; //First line of output System.out.println(employees.length); //Second through Fifth lines for(int i = 0; i < employees.length; i++) { System.out.println(employees[ i ].payEmp()); } } } a) First Line Output b) Second Line Output c) Third Line Output d) Fourth Line Output e) Fifth Line Output

a) 4 b) 25 c) 100 d) 36 e) 200

Consider: public class FirstProgram { public static void main(String[] args){ String s1 = "Java Programming Rocks!"; String s2 = "!@#$%&";String s3 = "0123456789"; // First line int size = s3.length() - s2.length() + 4; System.out.println(size); // Second line System.out.println(s3.charAt(7)); // Third line int iSum = s1.indexOf('P') + s3.indexOf('5'); System.out.println(iSum); // Fourth line String sSubstr = s1.substring(2,4) + s3.substring(0,5); System.out.println(sSubstr); // Fifth line boolean bEquals = s3.substring(2,6).equals("2345"); System.out.println(bEquals); } } a) First line prints: b) Second line prints: c) Third line prints: d) Fourth line prints: e) Fifth line prints:

a) 8 b) 7 c) 10 d) va01234 e) true

Consider: public class BadProgram { // error 1 // this method should return nothing public static myMethod(){ System.out.println("I am here!"); } public static void main(String[] args){ myMethod(); // error 2 // should print a1 but prints 98 instead System.out.println('a' + 1); // error 3 // should print undefined System.out.println(1/0); // error 4 // str should be equal to z but there is an error String str = 'z'; // error 5 // add these three numbers together and print the result sint i = 2; j = 3; k = 4; System.out.println(i + j + k); } } a) First Error Type? b) Second Error Type? c) Third Error Type? d) Fourth Error Type? e) Fifth Error Type?

a) Compile b) Logic Error c) Runtime d) Compile e) Compile

Consider Method: public int doStuff(short i) { int ret = 5; ret += ret + i; return ret; } a) Method's name? b) Method return type? c) How many arguments does this method take? d ) if called using doStuff(3), the method returns?

a) doStuff b) int c) 1 d) 8

add(object)

appends an element to the list

primitive types

boolean, byte, char, short, int, long, float, double

Which statement(s) will print "Hello World!"? a) System.out.println(Hello, World!); b) print("Hello, World!"); c) System.out.println("Hello" + ", World!"); d) System.out.println("Hello, World!");

c, d

recursive method

calls itself in its method body

ASCII Characters

char a = 'b' + 3; == char a = 'e'; char b = '2' - 3; == char b = '/'

instances of objects

created upon using the new keyword

Which of these lines ONLY declares but does not initialize a 2D array of type int? a) int[][] x=new int[][]; b) int[][] x={}; c) int[] x; d) int[][] x;

d

Predecrement

decrement variable by 1 before variable has been used (--x)

object variables

do not actually store an object, actually store the address of an object's location in the computer's memory (references/pointers)

Given a string s with a value of "Yay Coffee!" which statement returns the substring "Coffee"? a) s.substring(5,10) b) s.substring(4) c)s.substring(4,11) d) s.substring(5,11) e) s.substring(4,10) f) s.substring(5)

e

True/False: A String is a primitive type.

false

True/False: if the variable a is an int in this case, the following two statements are equivalent. if(a == 0){} if(a = 0){}

false

loop without bracket prints...

first line only

fractal

geometric figure that can be divided into parts, each of which is a reduced-size copy of the whole

constructors

implemented to specify behavior upon making a new object

Bubble Sort

in each pass, puts on element in its right place

this

in method or constructor, refers to a specific instance of an object

Postincrement

increment variable by 1 after variable has been used (x++)

boolean isEmpty()

indicates if the list is empty

add(index, object)

inserts given value at give index, shifting subsequent values right

initialization

int x = 49; char a = '?';

declaring

int x; char a;

array list

int[] numbers = new int[5]; ArrayIntList list = new ArrayIntList();

toString

method in an object allows for the object to be displayed as a string

Reads from a String

new Scanner("input.txt")

Read from the Keyboard

new Scanner(System.in)

Reads from a File

new Scanner(new File("input.txt"))

Will System.out.println('a' + 2); print a2?

no

Strings

objects

iteration

one time completely through sorting

else if statement

only executed if both of the following are true: -the if statement (or else if statement) above was not executed -the condition of the else if statement is true

absolute path

path name starting at

relative path

path name starting at the working directory

clear()

removes all elements from the list

object remove(index)

removes the element at the specified position (and returns it)

object remove(object)

removes the element that corresponds to the given object (and returns it)

modulo operation

returns remainder of divison

object get(index)

returns the element at the given position

index indexOf(object)

returns the index of the first occurrence of the specified element

int size()

returns the size of the list

argument

the instance passed to the method during runtime

True/False: Any switch statement can be replicated using if/else if/else statements.

true

if/else statements

used to do something if a condition is true and something else if the condition is false

reference variable

when one is assigned to another, the object is not copied, both refer to the same object


Conjuntos de estudio relacionados

CSC Healthcare Informatics Exam #2

View Set

Mental Health practice Questions

View Set

Tough, though, thought, through, thorough and throughout

View Set

Geography Trails (South America)

View Set

Maternity and Women's Health Nursing - Women's Health

View Set

Chapter 3: International Financial Markets

View Set

Chapter 11: Innate and Adaptive Immunity

View Set