CS 211 - Final Review

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

If a class has this as their header: public class SomeClass implements Comparable<ArrayList<Integer>>, what should the method header of SomeClass's compareTo method be? public int compareTo(ArrayList<Number> obj) public int compareTo(ArrayList<Integer> obj) public int compareTo(ArrayList<Object> obj) public int compareTo(Collection<Integer> obj)

public int compareTo(ArrayList<Integer> obj)

what is exception handling? what are some failure cases (who handles them?)

remove error handling code from "main line" of program • Invalid method arguments (compiler/programmer) • Out of bounds array index (compiler/programmer) • Division by zero (programmer/user?) • String parsing errors (programmer/user?) • The new keyword not allocating memory (?) Java uses the framework of exceptions to deal with all of these issues

What is the difference between capacity and size when it comes to data structures? There is no difference: they both represent the total number of elements the structure can hold before needing to expand size keeps tracks of how many items it can hold before expanding; capacity keeps track of the number of elements size tracks the number of elements; capacity tracks the total number of elements it can hold before needing to expand There is no difference: they both represent the number of elements in the structure

size tracks the number of elements; capacity tracks the total number of elements it can hold before needing to expand

Which character do we use to denote that one generic should be the sub/super class of multiple other classes , & The space None of the above

&

what are the main interfaces of Java collection class?

- The java.util.Collection and java.util.Map interfaces are the two main "top-level" interfaces of Java collection classes

What does the following code print? double[] x = {1.0, 2.0, 3.0}; double[][] y = {x,x}; y[1][1] = -4.0; for(int i=0;i<x.length;i++) { System.out.print(x[i]+" "); } System.out.println(); Choice 1 of 4:1.0 -4.0 3.0 Choice 2 of 4:1.0 2.0 3.0 Choice 3 of 4:Nothing, this code contains a syntax error Choice 4 of 4:None of the above.

1.0 -4.0 3.0

Say int[] someArr = {7, 2, 4, 1, 3, 6, 5} is put through a not-in-place selection sort method. What will someArr look like once the sorting method has gone through three numbers (someArr is sorted in ascending order)? 1, 2, 4, 7, 3, 6, 5 1, 2, 3, 7, 4, 6, 5 7, 2, 4, 1, 3, 6, 5 1, 2, 3, 7, 4, 6, 5

7, 2, 4, 1, 3, 6, 5

Lambda VS anonymous class?

: lambda expressions do not inherit fields or members, they are independent of the class hierarchy. They are functions (not methods) without an enclosing class/instance. (look at printed examples)

Which tag can make a method run depending on the number of unit tests there are? @Ignore @BeforeClass @After @Test

@After

What is a Nested class? what are the two types of nested classes?

A nested class is a class defined within another class. (Both classes and interfaces may be nested) • Static nested classes • Non-static nested classes, a.k.a. inner classes • A nested class may be declared private, public, protected or have the default access modifiers (just like fields...) • Enclosing and nested classes can access each other's private fields and methods(!) • Use cases: grouping related classes together, increasing encapsulation, reducing "single use" .java files

A recursive method that does not check for a _____, or that misses the _____ is a _____

A recursive method that does not check for a base case, or that misses the base case is a logic error

checked vs unchecked exceptions

Checked exceptions - exceptions that must have explicit handling instructions provided by the programmer. This is checked at compile time. • Unchecked exceptions - exceptions that do not need any explicit handling instructions...because the default action should be "stop the program!" Terminology: "explicit handling instructions" are called handlers. It is not an error to write a handler for an unchecked exception, but it is an error to not write a handler for a checked exception (compile time).

What is something linear searches are better at than binary searches? Linear searches can search through all arrays, no matter how the elements are organized Linear searches have a shorter time complexity Linear searches searching through larger arrays quicker than binary searches Linear searches are more memory efficient than binary searches

Linear searches can search through all arrays, no matter how the elements are organized

Linear (sequential) search VS Binary Search

Looking for a particular item (target) in a collection of elements is one of the most common tasks in programming. The basic approach is sometimes called linear or sequential search VS Binary: If the data to be searched is sorted (in order), the searching can be made easier Binary search can be much faster! (O(log n)) Two questions: • How do we put things in sorted order efficiently • Which is faster: sorting and then searching, or just linear search?

Which sorting algorithm is the most memory taxing? Insertion sort Selection sort Merge sort Quick sort

Merge Sort

Which if the following sorting algorithms are guaranteed to have never have an O(n2) time complexity? Insertion sort Selection sort Merge sort Quick sort

Merge sort

Class level VS method level

Method- local inner classes: • When we write a class definition inside a method body, it's known as a method-local inner class, local class, or sometimes local type. • Like local variables, the scope of a local class is restricted to within the method • A method-local inner class can only be instantiated within the method where it is defined (the instance may persist after the method returns however).

throwing checked excpetions

Methods which can throw checked exceptions need special syntax when they are declared: • The compiler needs to know what to check for • The programmer needs to know what handlers to write Unchecked exceptions don't need this syntax

Can Collections be sorted?? is this possible? Collections collection = new Collection( )

NO, Collections can't be sorted Lists and ArrayLists can! That example is NOT POSSIBLE => need to cast to list to be able to sort it that way

What does the following code print? double[] x = {1.0, 2.0, 3.0, 4.0}; System.out.println(x); Choice 1 of 4:{1.0, 2.0, 3.0, 4.0} Choice 2 of 4:null Choice 3 of 4:Nothing, this code contains a syntax error Choice 4 of 4:None of the above.

None of the above.

Which of the following sorting algorithms uses a pivot? Insertion sort Selection sort Merge sort Quick sort

Quick sort

What is recursion?

Repetition is a common control flow feature. Iteration involves repeating the same block of code in a loop. Recursion involves methods which call themselves. A common problem solving technique is to break the problem into smaller problems, find the solution to the smaller problem, combine the smaller solutions into an overall solution - "divide and conquer" strategy If the "smaller problem" has the same form as the original problem, we can apply the same procedure over again - recursion. When does this stop? When we've hit a small enough problem that the answer is direct - a base case. A method that calls itself is a recursive method. The call is a recursive call or recursive invocation

how would you Find the "maximum" element in an array of int, double, char, String... WITHOUT using relational operators (>, <=, ...) for reference data types

Solution: • Create an interface which defines a method for comparing any two items... aka, java.lang.Comparable with the int compareTo(...) method • For any class we make, implement Comparable and override compareTo to define the behavior we want! • We can write a method which takes Comparable arguments and use compareTo to find the maximum

what determines checked or unchecked?

Subclasses of Error and RuntimeException are unchecked. Everything else is checked

What can you use to define an object's upper bound to ClassOne and its lower bound to ClassSeven? T extends ClassOne & Comparable<? super ClassSeven> T super ClassOne & T extends ClassSeven T extends ClassSeven & Comparable<? super ClassOne> T extends ClassOne & T super ClassSeven

T extends ClassOne & Comparable<? super ClassSeven>

when to uses recursion vs itertation?

Tail Recursion: When the last action performed by a a recursive method is a recursive call, we call it tail recursion • This repeats the original call, with a change in the parameter. We can re-write this code in an iterative form that may be more efficient (in terms of memory) • Some languages (not Java) perform this optimization for you

What is the Vector class?

Talking about collections: • The Vector class implements a dynamic array data type, much like ArrayList • The primary difference between the two classes is that access to elements of the Vector class is synchronized by default (thread safe) • The Vector class guarantees that its capacity will be greater than or equal to the number of elements it contains at all times • If a Vector needs to grow, it grows by its capacity increment (if not specified, doubles). Default initial capacity is 10 elements.

What part of Java is responsible for running recursive calls? None of the below Both the JVM and the Java compiler The Java compiler The JVM

The JVM

What is the relationship between interfaces (lists) and implementing classes (ArrayLists, LinkedLists)?

The List interface: • A list (sometimes called sequence) is a data structure that maintains an ordering over its elements, which allows for duplicates • The List interface represents an ordered Collection that can contain duplicates the relationship: • Several classes implement the List interface (ArrayList, LinkedList, Vector...) • ArrayList and Vector are resizable-array implementations of List • LinkedList is a linked-list implementation of List

what is unit testing?

The goal of testing is to design tests that exercise defects in the system and to reveal problems • It is impossible to completely test a nontrivial system • Testing needs to be performed under time and budget constraints UNIT testing specifically: Definition: The process of individually testing a minimal part (or unit) of a program, typically a single method. Unit testing is typically conducted by creating a test harness, a.k.a. test bench: a separate program whose sole purpose is to check that a method returns correct output values for a variety of input values. Each unique set of input values is known as a test vector

Consider the following lines of code. Which (one) of the following statements is true? Object foo; /* ... some additional code here ... */ AnotherClass ac = (AnotherClass)foo; Choice 1 of 4:The last line will always be a compilation error. Choice 2 of 4:The last line will only be a compilation error if AnotherClass is not the superclass of Object. Choice 3 of 4:The last line will only be a runtime error if foo does not reference an object that is type-compatible with AnotherClass. Choice 4 of 4:This code will always compile and run without any error.

The last line will only be a runtime error if foo does not reference an object that is type-compatible with AnotherClass.

what is the scope of a Generic class?

The scope of a generic class's type parameter is the entire class. A generic type parameter can even be used within a generic type specification:

Which of the following doesn't happen when a method is called? The syntax of that method is checked Pausing the currently executing block of code Make memory for the local variables/parameters Running the method

The syntax of that method is checked

<T> is essentially the same thing as <T extends Object> True False

True

All custom exceptions are just subclasses of the Exception class. True False

True

The main distinction between Sets and Lists is that while Sets can't have duplicate items, Lists can. True False

True

There are instances where linear searches and binary searches can take approximately the same amount of time. True False

True

When recursive methods are tail-ended, that means an iterative version of it can be made. True False

True

How do we tell the compiler we want an ArrayList variable that can contain anything that is type compatible with Number?

Using wildcard Syntax! • Wildcards can be used in the type parameter of method parameters, return values, variables or fields to indicate type compatibility • The syntax for a wildcard is the question mark symbol (?) • The wildcard is a "placeholder" for the actual type, as determined at run time Usage: ArrayList mal; mal = new ArrayList(); //OK mal = new ArrayList(); //OK mal = new ArrayList(); //Error!

what is the call stack

What happens when a method is called inside another method? Add another stack frame! • What happens when a method calls itself? Exactly the same thing.

Which of the following methods apply to all data structures that are children of Collection? (E is a generic type) add(E e); add(int index, E e); poll(); getFirst();

add(E e);

Which of the following assert methods would have JUnit consider the method it's in a passed unit test? Assume: Object o1 = new Object(); Object o2 = new Object(); Object[] oArr1 = {o1, o2}; Object[] oArr2 = {o1, o2}; assertFalse("message", 1 == 2); assertEquals("Message", 1, 2); assertSame("message", o1, o2); assertArrayEquals("message", oArr1, oArr2);

assertArrayEquals("message", oArr1, oArr2);

What is Erasure?

has to do with generics in java: When the compiler translates a generic method or class into Java byte code, it removes the type parameter section and replaces the type parameter with actual types • Process called erasure (because the generics are "erased" and only "plain" Java code remains) • Type parameters are replaced with type Object unless "otherwise specified"** • Why does this work? Inheritance hierarchy!

Java supports exceptions through a ____ . what are the classes?

hierarchy of classes - The Throwable class is the superclass of all errors and exceptions in Java. It has two subclasses: • The Error class - representing critical errors which are difficult or impossible to recover from, where the default response should be to immediately stop the program (e.g. OutOfMemoryError) • The Exception class - representing less serious / more common situations that should be handled gracefully if possible, but still represent something "out of the ordinary" happening (e.g. FileNotFoundException) : error and exception are terminology as well as class names (like object and Object)

What import would do nothing to help you create a new JUnit test class? import org.junit.*; import static org.junit.Assert.*; import org.hamcrest.core.*; import org.junit.Assert.*

import org.hamcrest.core.*;

Static nested classes

one of the two nested class types: • Like static methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class • Static nested classes are accessed using the enclosing class' name:

Inner Classes

one of the two types of nested classes: • An inner class is associated with an instance of the enclosing class and has access to instance methods and data • In order to instantiate an instance of an inner class, an instance of the enclosing class needs to be instantiated first! • The resulting new syntax looks...yuck.

what are Generics?

problem generics try to fix: - Write a method to display an array of (integers, doubles, floats, longs). • Bad* solution: Overloaded methods The only difference between the overloaded methods was the data type of the parameter: everything else was exactly the same => write code that is independent of the data type of some variables? Yes! Using generics Generics enable programmers to specify, with a single declaration, a family of related methods or classes • Generics also provide compile-time type safety that allows programmers to catch invalid types

Semantics and uses of Sets?

• A set is a data structure that contains no duplicates. • Ordering is not important, but checking if a set contains an item or not should be fast. • The collections framework contains the interface Set and several implementing classes, such as HashSet and TreeSet. • Each implementing class provides certain guarantees of performance, based on the underlying data structure in use. • Some implementing classes make additional requirements about the items they can store.

Semantics and uses of Stacks?

• A stack is a data structure which represents a last-in-first-out (LIFO) data structure. • The Stack class in Java is a subclass of Vector, and provides methods like push(), peek(), pop() and empty() in addition to the methods defined in Vector • The additional methods provide a way of interacting with the data structure that implements LIFO ordering while still providing all the functionality of a dynamic array collection

Priority Queues?

• A version of a queue where different elements may have different priorities. Examples: Hospital ER, plane boarding order, package shipping • The algorithms for adding, removing, and accessing elements are more complex than for ordinary queues (if done efficiently) • In Java, the class PriorityQueue<E> implements these features, and allows the priority to be specified by either a given Comparator or the items themselves (if they implement Comparable, the so called "natural ordering")

Generic methods (vs Generic classes)

• All generic method declarations have a type parameter section delimited by angle brackets ("<" and ">" ). Example: public static void printArray(T[] input){ • Each type parameter section contains one or more type parameters (also called formal type parameters), separated by commas. • A type parameter, or type variable, is an identifier that specifies a generic type name • The type parameters can be used to declare return type, parameter type, and local variable types in a generic method, and act as placeholders • Type parameters can only represent reference types, not primitive types* • Type parameter names throughout the method must match those in the type parameter section

What is an Anonymous inner class?

• An inner class declared without a class name is called an anonymous inner class • Syntax requires that you declare and instantiate at the same time • The general use case for anonymous inner classes are for when you need to override one or more methods of a class or an interface for a single use

What is ArrayList?

• ArrayList is actually a generic class! Usage: ArrayList mal = new ArrayList(); mal.add(0.0); mal.add(1.0); mal.add(-1.0); System.out.println(mal); //[0.0, 1.0, -1.0] • How were we able to use ArrayList without the generic syntax? "Backwards compatibility" • Note, we must use the reference type Double in the declaration, but (thanks to auto-boxing/unboxing) we can use primitives in the method arguments

what are common utility collection classes? (common methods)

• Class Collections provides static methods for manipulating collections • sort - puts the elements of a List in order • binarySearch - locates the position of an item within a List • reverse - reverses the order of elements in a List • fill - replaces every element of a List with a given item • copy - copies elements from one List into another List • min/max - returns the smallest/ largest element in a Collection • addAll - adds all items to a Collection • frequency - computes how often an item appears in a Collection • disjoint - returns true if two Collections share no elements

Merge Sort

• Divide array into two halves • Sort each half separately (recursion!) • Merge the halves together into one sorted array • By using "divide and conquer", we're splitting the problem size in half at each step (good chance to avoid O(N2))

defining exceptions

• Exceptions are just objects! • All exceptions are instances inherit from Throwable or its descendants • Generally, a programmer makes a new exception class by extending Exception, which makes a checked exception type

Generic classes (what the difference?)

• Generic classes allow us to use type parameters throughout an entire class. This means instances and references of the class will be parameterized. • A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section

Which sort does Java use?

• In the Arrays class, there are sort methods for arrays of primitives and reference types. • For primitive types, in-place sorting is a performance speed-up! Uses quick sort • For reference types, the size of references in memory should be negligible compared to the actual data, so merge-sort is used. • Method signatures (type can be any primitive or reference type): public static void sort(type[] a) public static void sort(type[] a, int first, int after)

What is java's framework for unit testing?

• JUnit is a Java framework for unit testing • Uses annotations to identify/configure methods that specify a test • A JUnit test is a method contained in a class which is only used for testing (a Test class) • To declare that a method is a test method, annotate it with the @Test annotation

what are Junit assertion methods?? (aka statments)

• JUnit provides static methods to test for certain conditions via the Assert class • These assertion statements typically start with assert (e.g. assertEquals()) • They allow you to specify the error message, the expected and actual result • They throw an AssertionException if the check fails

Quick sort

• Like merge sort, recursively divides arrays into chunks • Unlike merge sort, not necessarily exactly half of the array • One entry called the pivot • Ensure entries less than the pivot are to its left • Ensure entries greater than the pivot are to its right • After the above are true, pivot is in the right spot! • Works "in place" (unlike merge sort)

What are Linked Lists?

• Linked lists are a container-like data structure for storing collections of data in a sequential order • A linked list can be represented as a collection of data objects (nodes) tied together in a chain, with each object keeping track of the next object in the list Terminology: • The first node is called the head of the list, the last is called the tail • A node's sucessor is the next node in the sequence (the tail node has no successor) • A node's predecessor is the previous node in the sequence (the head node has no predecessor) • A list's length is the number of elements it contains (a list may be empty, length=0) • The LinkedList class implements the Collection and List interfaces (among others) • It uses a doubly linked list internally to store elements, and may contain duplicates

Selection Sort (implementation and analysis)

• Outer loop index (idx) goes from 1 to N elements, inner loop index goes from idx to N, so how many times do we loop? • (N-1)+(N-2)+(N-3)+...+2+1 = N*(N-1)/2, O(N2) for all cases • In each inner loop iteration we compare two numbers (inner index with current min). • In each outer loop iteration we swap once (found min with outer index

Insertions sort (implementation and analysis)

• Partition the array into two chunks, sorted and unsorted • Initially, the sorted part only contains the first element • The unsorted part contains everything else • At each iteration, • Remove the first entry from the unsorted part, and shift it left until it's no longer out of place • Very different algorithms, but same efficiency! For small arrays/collections, this is sufficient, but maybe not for larger datasets

try - catch notes

• Surround code that may cause an exception in a try block, follow with one or more catch blocks • If an exception occurs: if a matching catch exists, the first matching catch is executed . • If an exception occurs: if no matching catch exists, the JVM looks at the next closest scope for a matching catch (you can nest try-catch!) • If no exception occurs: all catch blocks are skipped. • You cannot have multiple catch blocks for the same exception ("____ has already been caught" compilation error)

GUIs in Java

• The Abstract Windowing Toolkit (AWT) is the original GUI package introduced with Java 1.0 in 1995. Still part of Java today. • Swing was introduced by Netscape and eventually merged with Java 2.0. Still part of Java today. • JavaFX was introduced in 2008 as a replacement for Swing/AWT. Additionally attempted to unify development for mobile, web, and desktop (with arguable success). Not integrated into Java until 2018, and now exists as a separate project with a separate team. We will not be discussing JavaFX today

What is the collection framework?

• The Collections framework is a group of classes and interfaces for modeling and implementing data structures, along with algorithms for storing/ manipulating data • A collection is one of several data structures that can hold references to other objects • Usually, a collection contains references to objects that are all of the same type • The implementations in java.util tend to be robust, performant, and flexible

What are the Inner class variants?

• There are three different types of inner classes, distinguished by how and where you define them: • Inner classes - named classes defined as (non-static) members of an enclosing class. • Method-local inner classes - named classes defined within a method. • Anonymous inner classes - unnamed inner classes (typically defined within a method, but not always)

Lambda Expressions

• Work with functional interfaces: • An interface with a single abstract method • Lambda expressions treat code as data • Syntax (this is an expression!): (argument-list) -> {body} • Three components: • Argument-list: Can be empty or non-empty • Arrow-token: links argument-list and body • Body: Contains expressions and statements. If it's a single expression, then no curly-braces are needed

what are common utility collection interfaces? (common methods)

• add - add a single element to the collection • addAll - add all the elements of one collection to another collection • remove - remove a single element from the collection • removeAll - removes all copies of multiple elements • retainAll - removes everything except what's given • toArray - turns a collection into an array (2 versions!) • contains - checks if an item is one of this collection's elements • iterator - access elements one at a time, the old way of looping over collections

you can generate exceptions using ____

typically an exception is thrown using the throw keyword: The throw keyword engages Java's exception handling mechanisms, and acts a lot like the return keyword (in terms of flow control). Syntax: throw <Throwable instance>

Can Generic methods be overloaded?

yes, they may be overloaded as well!! • By non-generic methods that have the same method name and number of parameters. • By generic methods with different type parameter sections • (Can become confusing quickly...) • Which one should be invoked? • The compiler searches for the method declaration that most precisely matches the arguments given in the call

What is GUI?

• A Graphical User Interface (GUI) allows users to interact with a program through graphical environments instead of text-based terminals • A new set of metaphors ("Window", "Desktop", point-and-click) drastically changed the accessibility of computing technology • One of the reasons that OOP was so dominant as a programming paradigm was how easily GUI programming fit with OOP techniques

Semantics and uses of Queues?

• A queue is a data structure that models a waiting line, a concept important in Operating Systems, Event Simulation, User Interfaces, etc... • Organizes elements according to the order in which they were added • Supports first-in-first-out (FIFO) operations (first element added is the first element removed) • Items are added to the back and removed from the front of the queue

Void methods cannot be used recursively. True False

False

What is something a double linked list can do that a linked list can't? Assume there are linked list and doubly linked list classes, which store the nodes. Remove all of its elements in one statement Become a cyclical linked list (a list that forms a circle) Remove the first element without iterating through any nodes Add a node to the end of itself without iterating to the end of the list

Add a node to the end of itself without iterating to the end of the list

Which of the following statements about Java is NOT TRUE? (select all that apply) A. The .class file created by compiling on a Mac cannot be used on a Windows computer B. the java command checks which files need to be compiled by comparing timestamps C. The Java Virtual Machine (JVM) runs an emulations of the original computer Hava was developed on in the 1990's D. Java's syntax was modeled after Python's syntax, with improvements for readability

All are not true class files compiled on any operating system can be read by the JVM of any operating system. the java command does not check timestamps or compile files Java was developed before Python

If replaced with the T placeholder, what/which class(es) would not cause the method to produce an exception? public static <T> void printListContents(List<T> theList) {...} Object Integer Number All of the above

All of the above

Which of the following statements is true about enums? Choice 1 of 4:An enum type is a specialized, restricted kind of class. Choice 2 of 4:An enum type only defines constants, no methods or fields. Choice 3 of 4:An enum type is not allowed to define any constructor. Choice 4 of 4:An enum type can only be used within the file where it is defined.

An enum type is a specialized, restricted kind of class.

what is an exception? what causes an exception?

An exception is anything unexpected or unusual about a program's execution: a situation that is not normal. There are a variety of things that can cause an exception: • Programmer error - ex. array index out of bounds • User error - ex. entering a negative value for age, or unparsable data • Hardware error - ex. Out of memory/storage, component failure An exception should be handled by the programmer, if possible

Unchecked exceptions that can happen in a method need to be included in the method's header as an exception that can happen. A. True B. False

B. False

which is a valid difference between unchecked and checked exceptions? A. Unchecked exceptions don't need to be imported to be used, while checked exceptions do B. Unchecked exceptions are checked by the JVM, while checked exceptions are checked by the Java compiler C. Because Java can handle unchecked exceptions easily, methods producing unchecked exceptions cannot cause exceptions, even if they're not inside try-catch blocks; a property that checked exceptions do not have D. After finding lots of

B. Unchecked exceptions are checked by the JVM, while checked exceptions are checked by the Java compiler

Which of the following keywords can force an exception to happen? A. force B. return C. throw D. throws

C. Throw

Which correctly describes Collection and Collections, and their differences? A. Collection is a concrete class that serves as an initializable, bare bones data structure that many other data structures in Java extend, while Collections is a utility class that provides static methods for these data structures B. Collection is an abstract class that many other data structures in Java extend to use as a blueprint, while Collections is an interface that many Java data structures implement for basic data structure functionality C. Collection is an interface that has the baseline functionality for nearly all data structures in Java, while Collections is a utility class that provides static methods for these data structures D. Collection is a concrete class that serves as an initializable, bare bones data structure,

Collection is an interface that has the baseline functionality for nearly all data structures in Java, while Collections is a utility class that provides static methods for these data structures

Which of Java's exceptions are a checked exception? a. NullPointerException b. Exception c. ArrayIndexOutOfBoundsException d. FileNotFoundException

D. FileNotFoundException

what does java use to indicated excpetions handlers?

Exceptions are thrown // exceptions handlers catches exceptions in a try - catch block

Primitive types can be used as generics. True False

False

Queues are only first-in-first-out data structures. True False

False

Recursive methods are more memory-efficient than iterative methods True False

False

what does the finally block do?

If an exception occurs midway through a complex process we often want to shut down and clean up gracefully (files partly written, database connections active, etc). The (optional) finally block, placed after the last catch block, executes regardless of if there is an exception or not. Syntax:

When a recursive call is made, where does Java store it? It's stored in its own frame, which is in a stack specifically made for method calls It's stored in its own frame in the only stack Java has It's stored in its own inside the heap It's stored in the heap

It's stored in its own frame in the only stack Java has

Which interface does Collection extend? Comparable Iterable Repeatable Readable

Iterable

How do the recursive calls change behavior

Just know and do example code

Why is "overriding" sometimes called "dynamic polymorphism"? Choice 1 of 4:Which method is called is determined by the runtime type of the object. Choice 2 of 4:The inheritance hierarchy isn't known until runtime Choice 3 of 4:The @Override annotation is parsed by the JVM, not the compiler. Choice 4 of 4:None of the above.

Which method is called is determined by the runtime type of the object.

Assume that arr is an ArrayList. Would this for-each loop execute? for (int i : arr) { System.out.print(i); } Yes because Java allows all data structures to use for-each loops by default No because the for-each loop only works with arrays, which arr is not No because the for-each loop only works with classes that implement the Iterable interface and arrays, which the ArrayList class is neither of Yes because ArrayList indirectly implements Iterable, which allows it to be iterable

Yes because ArrayList indirectly implements Iterable, which allows it to be iterable

Can you manually set the type parameter for a generic call? and Can you have generic methods (with different formal type parameters) inside a generic class?

Yes! and Yes!

Are there "lower bounds" as well as upper bounds? and Can you specify a wildcard without any bounds?

Yes! and Yes! In this example, we've specified that Number is an upper bound on the types that are valid for this ArrayList. We can also use wildcards to specify lower bounds, or no bounds at all!

Common errors in recursive code? (what to look for)

do zybooks and just know what recursion methods look like


Kaugnay na mga set ng pag-aaral

Social Media Marketing Chapter 3

View Set

Listening Guide Quiz 17: Haydn: Trumpet Concerto

View Set

Medical Laboratory Science Review- Harr - Immunology

View Set

Algebra Module 3 linear equations

View Set

US History: Q3 - Lesson 4 - Assigment 8_Industrial Lifestyle: Trends

View Set

A Porra do Cursinho Inteiro (6 de Junho - 30 de Agosto)

View Set