CSCI 221 Final

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

Which expression correctly evaluates 13 < num < 30? (num < 13) && (num < 30) (num < 13) || (num < 30) (num > 13) && (num < 30) (num > 13) || (num < 30)

(num > 13) && (num < 30)

Given function Multiply(u, v) that returns u * v, and Add(u, v) that returns u + v, which expression corresponds to: Add(Multiply(x, Add(y, z)), w) (x * (y + z)) + w (x + (y + z) * w) ((x * y) + z) + w (x * (y + z) * w)

(x * (y + z)) + w

Which expression evaluates to false if x is 0 and y is 10? (x == 0) && (y == 10) (x == 0) && (y == 20) (x == 0) || (y == 10) (x == 0) || (y == 20)

(x == 0) && (y == 20)

Prefix Notation

+ 2 3

Arithmetic Operators

+, -, *, /, %, Math.pow(base, power)

Comments

// /**/

The numNegatives variable counts the number of negative values in the array userVals. What should numNegatives be initialized to? int[] userVals = new int[20]; int i; numNegatives = XXX; for (i = 0; i < 20; ++i) { if (userValues[i] < 0) { numNegatives = numNegatives + 1; } } userVals[0] No initialization needed 0 -1

0

What is the output? int n; for (n = 0; n < 10; n = n + 3) { System.out.print(n + " "); } 0 1 2 3 4 5 6 7 8 9 1 4 7 10 0 3 6 9 0 3 6 9 12

0 3 6 9

Exception Handler

The block of code that can handle the exception.

What does the void keyword signify in a method? The method can be accessed without creating the object of the class The method does not return any value The method is public and can be accessed from outside the class The method cannot have parameters

The method does not return any value

Finally block

follows a try block or catch block; always executes no matter if an exception was thrown

Array Initialization

int[] count = {1, 2, 3}; double[] values;

Initialize 2D Array

int[][] a = new int[row index][col index];

A(n) ___ provides abstract methods and no other code. abstract class base class polymorphic class interface

interface

A(n) _____ provides abstract methods and no other code. abstract class interface polymorphic class base class

interface

How to run

java programname

How to compile

javac programname.java

Which is an invalid access for the array? int[] numsList = new int[5]; int x = 3; numsList[0] numsList[(2*x) - x] numsList[x+2] numsList[x-3]

numsList[x+2]

Iterator

object enables a programmer to traverse a container/collection Iterator it = list.iterator(); can then go through elements in iterator with while loop

An ___ method shares the same name but a different number of parameters with another method in the same class. overloaded copied inherited overridden

overloaded

An ________ method shares the same name but a different number of parameters with another method in the same class.

overloaded

Which XXX is the proper default constructor? public class Employee { private double mySalary; XXX } public Employee( ) { double mySalary = 10000; } private Employee( ) { mySalary = 10000; } public Employee( ) { mySalary = 10000; } public Employee(double salary) { mySalary = salary; }

public Employee( ) { mySalary = 10000; }

Which class definition requires Square to follow the API of Shape? public class Shape implements Square public interface Shape public class Square extends Shape public class Square implements Shape

public class Square implements Shape

Which XXX method signature returns the student's GPA? public class Student { private double myGPA; private int myID; XXX{ return myGPA; } } private double getGPA( ) public double getGPA( ) public int getGPA( ) double getGPA( )

public double getGPA( )

Which expression doubles x? x += 2; x *= 2; x *= x; x *= x * 2;

x*=2;

Given string s is "Sunday", what is the ending value of char myChar? myChar = s.charAt(s.length() - 1); a y " No such character

y

implements != extends

you can extend a class, but you implement an interface a class can only extend one other class, but it can implement as many interfaces as you'd like

How many objects of type Car are created? Car mustang = new Car(); Car prius; int miles; Truck tundra = new Truck(); 0 1 2 3

1

Which lines demonstrate autoboxing ? 1 Integer intValue = 20; 2 double myScore = 30.0; 3 Double yourScore = myScore; 4 Character yourGrade = 'A'; 5 char myGrade = yourGrade; 2,5 1,3,4 3,5 1,2,3,4,5

1,3,4

To create a recursive definition

1. base case 2. recursive case

How many times is numberOfStudents() called if main() calls numberOfStudents(9)? public static void numberOfStudents(int num) { if (num >= 10) { System.out.println(num); } else { System.out.print("Bye"); numberOfStudents(num+1); } } 9 2 10 1

2

What is the ending value of the element at index 0? int[] numbers = new int[10]; numbers[0] = 35; numbers[1] = 37; numbers[1] = numbers[0] + 4; 39 0 35 37

35

What is the ending value of numItems if myChar = 'X'? switch (myChar) { case 'W': numItems = 1; case 'X': numItems = 2; case 'Y': numItems = 3; case 'Z': numItems = 4; } 2 3 4 9

4

What is the size of groceryList after the code segment? ArrayList<String> groceryList; groceryList = new ArrayList<String>(); groceryList.add("Bread"); groceryList.add("Apples"); groceryList.add("Grape Jelly"); groceryList.add("Peanut Butter"); groceryList.set(1, "Frozen Pizza"); 4 3 Error: Index out of bounds 5

4

Given ArrayList<Integer> numList (4, 6, 1, 0), what are numList's contents after the following operations: if(!numList.isEmpty()){ numList.remove(2); } numList.remove(1); 4, 0 1, 0 4, 6, 0 4, 1, 0

4, 0

What is output? ArrayList<Integer> numList = new ArrayList<Integer>(); int count; for(count = 1; count < 10; ++count) { numList.add(count); } System.out.println(numList.get(4)); 5 4 Error: Index out of bounds 6

5

Given Deque<Integer> intDeque with elements [3, 4, 5], what is output? System.out.println(intDeque.peekLast()); System.out.println(intDeque.peekLast()); 5 5 3 3 3 4 5 4

5 5

What is the final value of y? int x = 77; int y = 4; if (x == 77) { y = y + 1; } if (x < 100) { y = y + 1; } if (x > 77) { y = y + 1; } y = y + 1; 5 6 7 8

7

Given that integer array x has elements 4, 7, 3, 0, 8, what are the elements after the loop? int i; for (i = 0; i < 4; ++i) { x[i] = x[i + 1]; } 7, 3, 0, 8, 4 4, 4, 7, 3, 0 7, 3, 0, 8, 8 Error: Invalid access

7, 3, 0, 8, 8

How many elements are in the array? int[][] userVals = new int[2][4]; 2 8 4 6

8

Equality Operators

==, !=

Which is true? An interface can implement multiple classes A class can implement only one interface A class can inherit from multiple classes A class can implement multiple interfaces

A class can implement multiple interfaces

Which is true? A class can inherit from multiple classes. A class can implement only one interface. A class can implement multiple interfaces. An interface can implement multiple classes.

A class can implement multiple interfaces.

Which is true? A field cannot be initialized in the field declaration A constructor has no return type A default constructor has at least one parameter The Java compiler does not initialize fields to their default values

A constructor has no return type

Which is true? A constructor has no return type. A default constructor has at least one parameter. A field can not be initialized in the field declaration. The Java compiler does not initialize fields to their default values

A constructor has no return type.

Priority Queue

ADT (abstract data type) like a regular queue but each element is associated with a priority value and the element with the highest priority will be removed first. .insert: insert element at index .remove: remove first element

What does the compiler do upon reaching this variable declaration? int x; Allocates a memory location for x. Initializes x with the value -1. Converts variable x from a double to an integer. Increments x's value by 1

Allocates a memory location for x.

What is an Exception?

An exception is an event occurring during the execution of a program that disrupts the normal flow of a program's instructions.

Identify the correct syntax for declaring and creating an ArrayList of type String. ArrayList studentNames = new ArrayList(); ArrayList = new ArrayList studentNames (); ArrayList studentNames(); ArrayList = new ArrayList();

ArrayList studentNames = new ArrayList();

What is Autoboxing?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

Method

code that can be called to perform actions

Koch Snowflake Recursive Pattern

Base Case: straight line Recursive Case: 1. divide into 3 parts 2. turn left 60 degrees 3. turn right 120 degrees 4. turn left 60 degrees

Array Search (Ordered) - Binary Search

Best: 1 Worst: Log(N)

Array Search (Unordered)

Best: 1 Worst: N Avg: 1/N

Two arrays, itemsNames and itemsPrices, are used to store a list of item names and their corresponding prices. Which is true? Using two arrays saves memory versus using one array. Both arrays should be declared to have the same number of elements. The item names should appear in both arrays. Both arrays should be of the same data type.

Both arrays should be declared to have the same number of elements.

Which is true? Concrete classes cannot be inherited. Concrete classes do not have any abstract methods. Concrete classes cannot be instantiated. Concrete classes do not have any member methods.

Concrete classes do not have any abstract methods.

Which is true? Concrete classes cannot be inherited. Concrete classes do not have any abstract methods. Concrete classes do not have any member methods. Concrete classes cannot be instantiated.

Concrete classes do not have any abstract methods.

The Sierpinski Triangle uses what type of triangle? Equilateral Triangle Scalene Triangle Egyptian Pyramid Bermuda Triangle

Equilateral Triangle

What is the output? public static void main(String[] args) { for (int i = 0; i < 3; ++i) { System.out.print(i); } System.out.print(i); } 0123 012 Error: The variable i is not declared in the right scope 0122

Error: The variable i is not declared in the right scope

What is output? public class RecursiveFactorial { public static int factorial(int factValue) { if (factValue <= 0) { return 1; } else { return factValue*factorial(factValue-1); } } public static void main (String [] args) { int userVal = -5; System.out.println("Factorial = " + factorial(userVal)); } } Factorial = 120 Error Factorial = 1 Factorial = -120

Factorial = 1

Which of the following activities can be accomplished using recursive algorithms? Going to the supermarket to buy groceries Writing a letter to a friend Harvesting crops Making lemonade

Harvesting crops

Pass-by-Value

Java creates a copy of the variable being passed in the method

Given Deque<String> userName with elements ["Len", "Bill", "Amy"], what is output? System.out.println(userName.getFirst()); System.out.println(userName.pollFirst()); System.out.println(userName.pollFirst()); Len Len Bill Len Bill Bill Len Bill Amy Len Len Len

Len Len Bill

What kind of method is incCount()? class ClassData { private int studentCount; ... public int incCount() { studentCount = studentCount + 1; return studentCount; } } Accessor Method Mutator Method Constructor Static Method

Mutator Method

Which calculation does not have a natural recursive solution? Factorial Greatest common divisor Percentage Fibonacci

Percentage

Given Queue<String> colorsUnlimited with elements ["Red", "Green", "Blue"], what is output? System.out.println(colorsUnlimited.peek()); colorsUnlimited.poll(); System.out.println(colorsUnlimited.peek()); Red Red Red Null Red Green Red Blue

Red Green

T/F: A catch clause cannot exist without a try statement

T

T/F: It is not compulsory to have a finally clause whenever a try/catch block is present.

T

T/F: The try block cannot be present without either a catch clause of a finally clause.

T

T/F: There cannot be any code present in-between the try, catch, and finally blocks.

T

A programmer wants to access the fields and methods of one class from another class. What should the programmer do? Use braces at appropriate places to increase the scope of the fields and methods Use public access modifiers to make access possible It is not possible to access the fields and methods of another class Define the fields and methods again in the other class

Use public access modifiers to make access possible

What is the output? public class Paints { public static void main(String[] args) { Deque<String> myColors = new LinkedList<String>(); myColors.addFirst("Violet"); myColors.addFirst("Indigo"); myColors.addFirst("Blue"); myColors.addFirst("Green"); System.out.println(myColors.removeLast()); System.out.println(myColors.removeLast()); } } Blue Green Violet Indigo Green Blue Indigo Violet

Violet Indigo

Which of the following errors may lead to infinite recursion, causing the program to fail? Writing a case that returns a value without performing a recursive call Writing a recursive method that does not always reach a base case Ensuring a valid input has been provided to the recursive method Covering all possible base cases in a recursive method

Writing a recursive method that does not always reach a base case

Which of the following errors may lead to infinite recursion, causing the program to fail? Writing a recursive method that does not always reach a base case Writing a case that returns a value without performing a recursive call Covering all possible base cases in a recursive method Ensuring a valid input has been provided to the recursive method

Writing a recursive method that does not always reach a base case

Given empty Queue<Integer> customerNums, what are the queue's elements after the following code block is executed? customerNums.add(5); customerNums.add(2); customerNums.add(6); customerNums.remove(); customerNums.remove(); [2, 6] [5, 2] [5] [6]

[6] *Queue is FIFO*

Fractal

a geometric shape made up of the same pattern repeated in different sizes and orientations

To make a Deque behave like a stack, which methods should be used for element insertion and removal? insertHead() and deleteHead() addHead() and removeHead() insertFirst() and deleteFirst() addFirst() and removeFirst()

addFirst() and removeFirst()

.push()

adds a new item to a stack at the "top" or closest position (stack s with N items -> s[N])

Cosmic Superclass

all classes defined without an explicit extends keyword automatically extend to the Object superclass

Interface

all methods in a class are abstract

The _____ case defined in a function stops recursion. terminal loop base start

base

static Method

belongs to class rather than object of class, can be invoked without creating instance of class, can access static data member and change it

Which is a primitive type? boolean String Integer Character

boolean

Primitive data types

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

The built-in Object class _____. defines multiple methods including toString() and equals() defines toString() and no additional methods is derived from class Super is the base class for most, but not all, classes

defines multiple methods including toString() and equals()

The built-in Object class _____. defines toString()and no additional methods is derived from class Super is the base class for most, but not all, classes defines multiple methods including toString()and equals()

defines multiple methods including toString()and equals()

Class

definition of a type (data + operations)

Which method has been overridden? public class Vehicle { public void setID(int pID) { ... } public String getName(){ ... } } public class Plane extends Vehicle { public Plane(){ ... } public void setID(int pID1, int pID2){ ... } public void getName(String name){ ... } public String getName(){ ... } } Plane() setID(int pID) setID(int pID) getName()

getName()

Which accesses the number of elements in groceryList? ArrayList <String> groceryList; groceryList = new ArrayList<String>(); groceryList.size groceryList.length groceryList.size( ) groceryList.length( )

groceryList.size( )

Which if branch executes when an account lacks funds and has not been used recently? hasFunds and recentlyUsed are booleans and have their intuitive meanings. if (!hasFunds && !recentlyUsed) if (!hasFunds && recentlyUsed) if (hasFunds && !recentlyUsed) if (hasFunds && recentlyUsed)

if (!hasFunds && !recentlyUsed)

Multiple Catch Blocks

if an exception occurs in the protected code, the exception is thrown to the first catch block that applies - the subsequent catch blocks will not run. Always put the most general catch block at the end of your catch statements

Which statement allows an ArrayList object to be used in a program?

import java.util.*;

Given ArrayList<String> mascots ("lion", "eagle", "badger", "snake"), what is output? for (int i = 0; i < mascots.size() - 1; ++i) { System.out.print(mascots.get(i) + " "); } 0 1 2 lion eagle badger snake lion eagle badger 0 1 23

lion eagle badger

Which reads an entire line of text into string myString? scnr.nextLine(myString); myString = scnr.next(); scnr.next(myString); myString = scnr.nextLine()

myString = scnr.nextLine()

Select mutator XXX to set the temperature. public class WeatherData { private double myTemp; XXX } private void setTemp(double temp) { myTemp = temp; } public void setTemp() { myTemp = 92.6; } public void setTemp(double temp) { myTemp = temp; } public void setTemp(int temp) { myTemp = temp; }

public void setTemp(double temp) { myTemp = temp; }

.printStackTrace()

returns message of exception as well as class name and line #

.getMessage()

returns pre-defined java message of exception that has been thrown

Which of the following is an appropriate method call? public void getDetails() { } int setDetails() { } setDetails(4, "Tim"); getDetails() = 20;

setDetails(4, "Tim");

What is output? public class RecursionExample { public static void printer() { System.out.println("hello"); printer(); } public static void main(String[] args) { printer(); } } hello hello hello hello hello hello stack overflow

stack overflow

Given string str1 and string str2, which expression is true? str1 = "Hi"; str2 = "Hello"; str1.compareTo(str2) < 0 str1.compareTo(str2) > 0 str1.equals(str2) (Comparison not possible)

str1.compareTo(str2) > 0 *returns < 0 if given string is shorter than compared string and returns > 0 if given string is longer than compared string*

Which XXX assigns the parameter to the instance member? public class Student { private double gpa; public void setGPA(double gpa) { XXX } } double gpa = this.gpa; gpa = this.gpa; this.gpa = gpa; this = gpa

this.gpa = gpa;

Throws/Throw Keywords

throws keyword declares the exception thats not being handled - use to postpone the handling of an exception - put in method declaration throw keyword throws an exception (can be newly instantiated or just caught) - used to invoke and expression explicitly - put in body of code

What is output? public class AgeCheck { public Boolean userAge(int age) { if(age >= 18) { return true; } return false; } public static void main (String [] args) { AgeCheck user = new AgeCheck(); System.out.print(user.userAge(19)); } } 19 Compile Error false true

true

try/catch keywords

try/catch block is placed around the code (protected code) that might generate an exception. try{ //protected code } catch (exception name){ //catch block }

Queue

FIFO structure; ordered and has access to first and last element

Runtime of growing an array (start w 1 item and create new array of size n+1 and copy over items)

Quadratic Runtime O(N^2)

Recursion

The process of a method calling itself in order to solve a problem.

What is Programming?

Sequence of instructions that specify how to perform a certain computation

How many objects are created in the following code? SurveyData newSurvey = new SurveyData(2); SurveyData oldSurvey = new SurveyData(); SurveyData currentSurvey; newSurvey.setAges(0, 45); newSurvey.printAgeData(); 1 2 3 4

2

What is the ending value of x? x = 160 / 20 / 4; 2 16 32 No value; runtime error

2

Infix Notation

2 + 3

Postfix Notation

2 3 +

What is the ending value of z? int x = 5; int y = 12; double z; z = (double)(y / x); 0.0 2.0 2.4 3.0

2.0

Relational Operators

>, <. >=, <=

A character variable's value is stored in memory as _____ . a graphical symbol a string a floating-point value an integer value

an integer value

Abstract Class

any class containing one or more abstract methods - if subclass defines all inherited abstract methods = complete - if subclass does not define all inherited abstract methods = abstract (& cant be instantiated)

Returns length of array

arrayName.length;

Null Value

denotes non-existence, default value for all reference types, not an instance of any type, cannot be declared, casted, or de-referenced

Null

denotes non-existence; default value for all reference types (null == null -> true) cannot declare something as null

ArrayList

dynamic array implementation in Java Defined in java.util package

Object Abstraction

encapsulate data fields and methods

Method Abstraction

encapsulate routine computations

Class vs. Object

every object is an instance of a class, which defines the data and methods used for/on the object

How do I indicate my class inherits from another superclass?

extends public class Child extends ParentClass

For-Loop Statements

for (type variable : collection){ } for (int i=0; i < 6; i++){ }

Koch Snowflake

fractal that begins with an equilateral triangle

item .next()

gets next item

Recursive Method Format

if (base case){ something; } else { recursive call }

.enqueue()

insert item in queue at tail or end

Object

instantiation of a class ( allocated in memory using new operator)

Java.util.Queue

interface that extends basic collection interface; provides additional insertion, removal, and inspection methods add(e) remove()

java.util.Dequeue

interface that implements queue; provides insertion and removal on both ends

java.util.Collection

interface to represent a group of objects; declares basic operations

Abstract Methods

method that has been declared by not defined

Constructor

method that shares the same name as its class - responsible for establishing a new class object with the appropriate initial values for its instance variables

Java Naming Conventions

mixed case; class names begin with capital letters, variable and method names begin with lower case letters

Method Overloading

multiple methods can have the same name but different parameter lists invalid when return type is being changed

static Keyword

non-access modifier for variables and methods

Base Case

prevents an infinite loop in recursion; the most "basic" form of the problem that can be solved without recursion

Object-Oriented Programming

programming paradigm based on concept of objects - object = a single container combining both data + behavior

Encapsulation

protective barrier that prevents code/data being controlled/changed outside of class - make fields private and methods public

Structure of every Java function

public class CLASSNAME{ public static void main(String[] args) { STATEMENTS; } }

Which XXX prints the time value in the following code? public class TimerClock { private int min; public void setTime(int newValue){ min = newValue; } XXX } public class CookingTimer { public static void main(String[] args) { TimerClock cookTime = new TimerClock(); cookTime.setTime(10); System.out.print("The timer is set for "); cookTime.printTime(); } }

public void printTime( ){ System.out.print(min + " mins."); }

this Keyword

reference to current object, helps differentiate when field names are ambiguous

.pop()

remove item from s[N-1]

.dequeue()

remove item in queue at head or front

void .remove()

removes item from underlying collection

Instance Variables

represent data associated with an object of a class

Static Typing

requires the programmer to define the type of every variable and every function parameter in a program's source code

.top() or .peek()

retrieve item from s[N-1] without removing it

Accessor (Getter) Method

returns information without changing variable

Useful ArrayList Methods

size() get(int index) add(Object e) - appends to end of list add(int index, Object e) remove(int index) iterator()

Integrated Development Environment (IDE)

software application with comprehensive facilities for software development

How Java code is run

source code -> compiler -> byte code -> interpreter -> result

Primitive Variable

stores actual value

Reference Variable

stores the location (memory address) of an object from a declared class

Object Variable/Type

stores the reference to the object

Inheritance

subclass inherits all fields and method from a superclass subclass can add new fields, methods, and override methods of superclass

Inside a subclass, how can I access my superclass?

super constructor: super(x, y) method: super.foo() data field: super.name

Switch Statement

switch(conditional expression) { case 0: something to be done; break; case 1: something to be done; break; default: something else to be done;

instance Operator

tests relationship between objects and classes - think "object is an instance of this class - yes or no?" object instance <ClassName>

static Variable

used for common property of all objects - gets memory once at the time of class loading a static variable that is not final can be modified

implements = binding contract

when you say a class implements an interface, you promise to define all methods declared in interface

While Loop Statement

while(x>0){ }

Inheritance Limitations

1. cannot inherit from more than one parent class 2. doesn't have ability to enforce the creation of only subclass object - required superclass object

What is y after executing the statements? x = 4; y = x + 1; x = 3; y = y * 2; 6 8 10 12

10

Implementing Interface

A class can implement more than one interface. That class must then implement all abstract methods defined by interface class ClassName implements InterfaceName

Overloading vs. Overriding

Overloading - done within same class; useful for processing different objects by same logic Overriding - done by subclass; useful for incorporating additional info into methods of superclass

Stack

LIFO structure, stores an array of elements but with only 2 main operations (push, pop) must import java.util.Stack

Runtime of doubling size of stack

Linear Time O(N)

Does Java have a Queue class?

No, it has an interface for Queues

Method Overriding

When a subclass modifies the implementation of a method defined in the superclass - same signature as method in superclass @Override private methods cannot be overridden

Double-Ended Queue (Dequeue)

can insert/remove items at either end; LIFO or FIFO structure

Update (Setter) Method

changes one or more instance variables when called

boolean .hasNext()

checks if there is another item

Abstraction

concept of exposing only the required essential characteristics and behavior


Conjuntos de estudio relacionados

Child, older adult, and intimate partner violence

View Set

VNSG 1323: Chapter 25 Prep U Questions

View Set

Practical 3 Study Guide - Lab 12

View Set

chapter 33 assessment and management of patients with allergic disorders

View Set

Module 11- Consumer Protection Laws

View Set

SDSU Anthropology 101 Week 7 Test

View Set