CMSC132 Final Exam Fawzi

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

How do you implement an iterator in a collection in Java

1. You implement Iterable 2. Override the Iterator method (and return an Iterator) 3. return a new Iterator 4. define variables for the current index in the iterator 5. define methods that access the collection, such as next(), hasNext(), and remove()

What does putting final before a method do?

Avoids the method from being overridden, not overloaded.

T/F You need to initialize the outer class to use a static nested class.

False. This is one of the important distinctions of static nested classes and inner classes, they do not need an instance of their outer class to be used.

T/F: An abstract class can be instantiated

False. You can not instantiate an abstract class.

What extra identifier do you specify on top of a try catch black to run code whether or not there is an exception?

Finally block. The finally block runs whether or not you ran into an exception, if if you run into an exception in the catch block, the finally block will run after it.

What is the difference between composition and inheritance

Inheritance is-a and composition is has-a. A dog is an animal, but a dog has a leg. So you would extend the animal class, but have "leg" as an inner class

How would you call the iterator for this Arraylist list = new ArrayList<>();

Iterator listIterator = new list.iterator();

Which binding type has its objects decided at runtime, rather than compile time?

Late Binding

Where are recursive calls stored in a memory diagram?

The call stack

"Sideways" casting is never allowed

True. You can't do that

Name some exceptions in Java

UnsupportedOperationException("error"); This is if you are yet to implement a method. ClassCastException ArrayStoreException when adding wrong type to an array

What is it called when you cast a subtype to a supertype?

Upcasting

How do you use Comparable in a class?

public class Student implements Comparable<Student> {

What method does the Comparable interface implement?

.compareTo()

Name two of the built in functions in a Collection

.shuffle() and .sort()

What is a collection in programming in simple terms? What is a collection?

A collection is a group of individual objects represented as a single unit.

What is a data structure?

A data structure is a class that is used to represent and store information in a specific manner. Keyword is specific.

What is a default method?

A default method is a default implementation of a method in an interface. If a class implements an interface with a default method, it is not required to provide an implementation for that method, but can override if necessary.

What is an abstract data type?

Abstract data type (ADT) is an entity that has values and operations. More formally, an abstract data type is an implementation of interfaces (a set of methods). Note that it is "abstract" because it does not provide any details surrounding how these various operations are implemented. An abstract data type is a blueprint for the data structure. It defines the data and the operations that can be performed on the data, but it does not specify how these operations will be implemented. An example of an abstract data type is a queue, which supports the operation of inserting items to the end of the queue as well as the operation of retrieving items from the front of the queue. Note, again, that we are not concerned with how these operations should be performed internally.

What is an interface?

An interface specifies a set of methods that another class must implement. They are polymorphic, and follow an is-a relationship. As an example, consider an animal interface. If an elephant implements the animal interface, we can perform tasks that are meant for animals with elephants (such as passing an elephant into a function that accepts animals).

How do you initialize a new ArrayList in Java?

ArrayList<Cat> catList = new ArrayList<>();

What is the name for the condition for when recursion stops?

Base case or Stopping case

What are the two types of errors, and what are their differences?

Checked Exceptions and Unchecked Exceptions. A checked exception may occur even if your code works perfectly fine, for example opening a file that does not exist. An unchecked exception is usually more serious, if your code is unchecked. These may be like NullPointerException or something.

What happens if you do not check the instances before downcasting, what error might you get, and does it run anyway, cause a compiler error, or a run time error.

ClassCastException during runtime.

What class implements the 'clone()' method?

Cloneable. To override the Object class' default clone method, you extend Cloneable and override the clone method with your own implementation.

What class do Set, Queue, Tree, etc all extend?

Collection Everything in the collections framework implements the Collection interface. This means that a declaration like Collection<String> l = new ArrayList<String>() is perfectly valid.

What is the variable declaration that takes in any collection in Java?

Collection<Integer> elements; Can be used like: elements = new ArrayList<Integer>(); elements = new LinkedList<Integer>();

What is a collection?

Collections are objects that group multiple elements into one unit.

What is the difference between Comparable and Comparator

Comparable is an interface for a collection to implement that contains a single method, compareTo(). CompareTo is used withen an instance of a class, and therefore only takes one parameter - the other object. int compareTo(T o) Comparator is an interface that carries out the comparison using compareTo() when given two objects

What is the difference between data abstraction and procedural abstraction?

Data abstraction deals with the nature and manipulation of data, hiding its complexities, while procedural abstraction focuses on the process or method of achieving a task, hiding the steps or algorithms involved. Both are used to simplify the design of software and enhance readability, maintainability, and reusability.

What is data abstraction?

Data abstraction is the concept in object-oriented programming that deals with hiding the complex implementation details of data structures and exposing only the necessary and relevant aspects to the user.

What is it called when you cast a supertype to a subtype?

Downcasting

What is Late Binding also known as?

Dynamic binding

What class should you extend to make an exception?

Exception class (checked exception). This must be used in a throw catch block.

T/F you can call remove() many times after calling next()

FALSE. If you use next(), you can only call remove() one time, and you can only use remove() once you have called the next() method.

Classes can only extend more than one other class if at least one of those classesis an abstract class.

False, under no circumstances ever can you extend more than one class.

Downcasting can be done implicitly.

False, you always have to purposely do it, or your code will not compile

T/F an outer class can not access the private variables of an inner calss

False. An outer class distinguishes itself from extending classes by allowing the ability to access private members.

T/F Instantiating an interface will compile but throw an error.

False. If you instantiate an interface, your code will not compile.

T/F Iterable is a class.

False. It is an interface

Will this code compile final int x = 8; int y = 21; x = (y + 7) / 4;

False. It will not compile

'super.super' will refer to the current object, treating it as an instance of theparent of the parent of the current class.

False. Super.super is not valid

T/F A regular non abstract class can have abstract methods

False. The entire class should be abstract.

T/F Subclasses inherit everything from their superclasses

False. They inherit everything that isn't private. When you extend a superclass, you can not access any of the private fields.

You can always use a lambda expression instead of an anonymous inner class.

False. This is because some methods like iterator are not functional, and have multiple methods

T/F Unchecked exceptions are generally for common exceptions that need to beaccounted for.

False. Unchecked exceptions in Java, which are primarily subclasses of RuntimeException, are generally used for programming errors and issues that are typically not anticipated or "accounted for" in regular program operation. Unchecked exceptions happen when your code in unchecked, and you should fix an underlying problem in your code. Checked exceptions happen in correct, checked code, but require try-catch for instances where a user might have a missing file or class, etc. Checked Exceptions are usually checked at compile time and represent conditions a user might want to catch. Checked exceptions are typically used for recoverable conditions and where a client can take some useful action concerning the exception. You would want to wrap these in a try catch block. IOException, SQLException, ClassNotFoundException Encourages developers to proactively handle exceptions which can lead to more robust and error-resistant code. Unchecked Exceptions are not checked at compile time, but instead at run time. You fix these by writing proper code NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, OutOfMemoryError. They can be caught, but it's often a better practice to fix the underlying problem that caused the exception rather than to handle it.

To sort an ArrayList of MyObject objects using Collections.sort, MyObject must have an implementation of the compareTo method defined in the class.

False. While you can implement comparable and override the compareTo method, you can also use the built in Comparator like this: List<Person> people = new ArrayList<>(); Collections.sort(people, sortByAge); Using Lambda: Comparator<Person> sortByAge = (p1, p2) => Integer.compare(p1.getAge(), p2.getAge()); Using Class: Comparator<Person> sortByAge = new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return Integer.compare(p1.getAge(), p2.getAge()); } };

T/F When you override a method, you are allowed to change the number of arguments.

False. You can not change the number of arguments, that would be overloading.

T/F You can extend more than one class in Java

False. You can only extend one class in Java

Constructors in subclasses must directly invoke the constructors of every singleparent class before initializing the instance variables unique to that subclass.

False. You only need to call super() for the direct super parent

T/F Missing an implementation for any method in an interface will compile but throw an error.

False. Your code won't even compile if you don't implement an interface method.

What are interfaces with one method implementation called?

Functional Interface

How do you iterate over a collection in Java?

If a collection implements Iterable, we can use a combination of .iterator and .hasNext() to iterate over a collection. ArrayList<Integer> arr = new ArrayList<Integer>(); Iterable<Integer> arrIterator = arr.iterator(); while(arrIterator.hasNext()) { System.out.println(arrIterator.next()); }

Does a queue have an iterator? What about lists, queues, or sets?

If something has an iterator, it extends Iterable. List, Queue, Set, etc all extend Collection, which extends Iterable. (that was a hard question)

What happens if there is no default constructor in a super class?

If there is no default constructor in your superclass, Java can not automatically insert super(), because of that, you need to manually type out the super() constructor initialization. This causes a compile time error.

Why do the wrapper classes for primitives exist?

In order to make collections of these values. Collections can only collect objects, not primitives.

What is the process of a clone method? Explain what happens inside of a clone method and have a good understanding of what it does.

Inside of a try catch block, define a new object with the same type as the current object, which is also what you want to return. You can either set it to null and build on it, or directly cast super.clone() into the current object type. You have created a shallow copy, now, you can add specific implementation for specific variables if you want them to be deep copied, or have some other cloning behavior for those values. Now you can return that object. In your catch block, check if there is a CloneNoteSupportedException, this will only be thrown if the Cloneable class is not extended, you can throw an assertion here.

Which block runs more often than the other?

Instance (non static) initialization blocks are run every single time an instance is created, compared to static blocks that run only once, the first time the object is created in memory.

How do you get an array length in Java?

Int length = arr.length;

How do you initialize an Integer wrapper class using the built in Integer methods?

Integer x = new Integer.valueOf(7)

What does calling ".values()" on an enum type do?

It returns an Array of the enum possible values

What is procedural abstraction?

Procedural abstraction is a type of abstraction in which the user is aware of what actions are being performed, but they are not told how the action is performed.

What is the difference between procedural abstraction and encapsulation

Procedural abstraction is when the user knows how to use a method, but not the exact method implementation, while encapsulation is hiding variables using private Encapsulation: Think of the BankAccount as a secure vault. You have some controls (methods) to interact with what's inside (the data), but you can't directly access or see the contents (internal state). Procedural Abstraction: Consider the process of depositing money as a black box. You put the money in (call the deposit method), and the system handles all the complex processes of updating your account balance. You don't see or need to understand these internal workings.

What are the two types of abstraction?

Procedural and Data Abstraction

Since you can't access private fields, what is an alternative keyword instead of private that would allow a subclass to access a field in the superclass.

Protected Protected allows us to limit the visibility of a variable, while still permitting subclasses to access that variable.

Are circular arrays more commonly used in queues or stacks?

Queues. This is due to their First In First Out nature.

What is this variable initialization called without a generic? List myL = new ArrayList();

Raw type. You can cast the elements in a raw type to another object without getting a runtime error. Java will permit us to add any type to the list. So B b = (B) myL.get(0); Will compile without an error - unlike if we did pass in a type other than B.

What are the three ways to copy an object in Java?

Reference, Shallow, and Deep Copy. Reference copy is when you set two objects equal to each other, like x = y, this only copies their reference in memory and any change to x is reflected in y. Reference copy copies reference. Shallow copy copies the structure of an object, but not the actual data. You can think of it as making a new copy of primitives, but maintaining references to mutable fields. This is what .clone does. Deep copying makes a unique, legit new copy that is unreferenced to the original object, and is not effected at all by when the first object is changed.

What are the two types of initialization blocks?

Static and Instance (non static) Initialization blocks

What is Early Binding also known as?

Static binding

Which would run first if they were both in a class, a static initialization block, or an instance (non static) initialization block?

Static initialization block. You can imagine it as first loading a class into memory (one time) and then initializing a new instance for every use case after. Loading a class into memory runs one time, and that is the only time a static initialization block runs. However, once the class has been loaded during a program run, it is never run again. It can be initialized again, however. When you initialize a class, a couple things happen. You allocate memory, initialize the fields, among other things, and then you run the Instance Initialization Block right before the constructor. You can clearly see that the static initialization block will only ever run one time, and before the class is initialized, so before the first instance initialization block ever runs.

What is the difference between a static nested class and inner classes?

Static nested classes can be initialized without a reference to the outer class, which is not the case with inner classes.

Code a clone method for an object now. Flip to see the answer

Tada!

Practice implementing a method normally, with an inner class, and then with a lambda expression. Flip this card when you are done.

Tada!

Practice initializing an enum with a constructor

Tada!

What are the two entities stored in a LinkedList node?

The data stored in that node, and the reference to the data in the next node. T data Node next

What are the three steps to an equals method? What are the three things you have to implement?

The equals method signature should take in an Object obj 1. You must first check if obj == this. This checks if the object being compared is the current object. 2. You must second check if obj is not even an instance of the current class. This would mean that it is definitely not equal. 3. You should then cast obj into the current class type, and then compare the equals of the subvariable, with that new casted type.

In memory, where are are nodes stored?

The heap

What is Early Binding?

The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. Basically, the object type is what it was inserted into, and it doesn't retain its original type. Faculty carol = new Faculty("Carol Tuffteacher", 458, 1995); Person p = carol; System.out.println(p.toString()); Would use Person's toString method.

Does this code throw a compile error? Animal[] animals = new Dog[1]; animals[1] = new Cat();

Trick question, but false. When you create an ArrayList and initialize it with an ArrayList of a specific type, say an ArrayList of Dogs into Animals it causes a compile error, meaning your editor will have a red line under it telling you it's wrong. When you create an Array of Dogs and pass it into an Array of Animals, then add a Cat, you actually get a runtime ArrayStoreException, not a compile error. To summarize when Collection errors occur with different types, you get a compilation error when initializing the ArrayList, which works fine with an Array, but you get a runtime exception when you try to add a different value to it. Here List<Animal> animals = new ArrayList<Dog>(); // Compilation error Animal[] animals = new Dog[1]; animals[1] = new Cat(); // Throws ArrayStoreException at runtime

T/F the next method in an iterator in Java returns the currentIndex first, then the next element.

True

Will instanceOf also return true if the object being compared is itself?

True

T/F A class can be used as a blueprint for another class.

True, a class can extend another class and implement functions from its super class in an is-a relationship.

Can an inner class extend its outer class?

True.

T/F Upcasting is always allowed

True. Because of the is-a relationship between the two

T/F Super() must be the first statement in the subclass constructor.

True. It must be the first statement in the subclass constructor. If not explicitly called, the compiler automatically inserts a call to the no-argument constructor of the superclass.

T/F Anonymous classes can't be referenced later on

True. They are not given names, so you can not extend them later on.

T/F If GT is a generic type, and B is a subclass of A, GT<A> is not a subtype GT<B>?

True. When you use two related classes in a generic type, they do not automatically keep that same relation. A famous example is that ArrayList<String> is not a subtype of ArrayList<Object> ArrayList<String> strL = new ArrayList<String>(), ArrayList<Object> objL = strL ^ Is an illegal statement (ArrayList is invarient)

T/F instanceOf is not a method

True. instanceOf is not a method, it is an operator, similar to "+," or "*"

What is an automatic alternative to using an Iterator?

Using a forEach loop (enhanced for loop) Using forEach(T object : objects) uses the iterator by default. ArrayList<Integer> arr = new ArrayList<Integer>(); for(int arrValue : arr) { System.out.println(arrValue)); }

Which binding type allows us to use polymorphism and why?

Using late binding allows us to use polymorphism. For example, imagine you created an array of type Person, and you added a Person, Student, and Faculty into that new array. With Early (Static) Binding, when you call on a specific index to run a method, it will use the Person class' methods, rather than the type it was initially assigned. Which is why with late binding, you can now use polymorphism.

Explain what putting the final keyword does for classes, methods, and variables.

When you add final to a class, you avoid classes from extending it When you add final to a method, you avoid it from being overriden, When you add final to a variable, you avoid it from being changed.

Do enums have static members? What about instance members?

Yes, enums can have both

Does java automatically reclaim memory used by unreferenced objects?

Yes, this is called Garbage Collection and is done automatically. It is performed periodically and is not guaranteed to happen. This is carried out using destructors. These are void methods with the name finalize() and are only invoked if garbage collection occurs. (These are from Kumar's CMSC132 nots, not from Fawzi's lectures, but good to know anyway).

Explain how you would use the Iterator and Iterable interfaces in Java when writing a collection.

You would first implement Iterable in the collection itself. This allows you to override the .iterator() method, which returns Iterator. You then define an instance sub class that implements Iterator. This allows you to define the currentIndex, and add the hasNext() and next() methods.

How would you check that a method is-a -nother type or is a subclass of it in Java?

You would use instanceOf to verify that a class is an instance of another class. if (p instanceof Animal) { /* Code to be executed */ }

Downcasting isn't always possible, how do you check if downcasting is possible?

instanceOf. This checks if the object you are downcasting is the same instance as what you are casting it to. This is also called Safecasting. if (obj instanceof Student) { Student student = (Student) obj; System.out.println(", admission year is " + student.getAdmitYear()); }


Kaugnay na mga set ng pag-aaral

8th Grade Parts of Sentence study guide

View Set

English Grammar Secrets: question tags

View Set

Longest rivers in European countries

View Set