CMPS2800 Final Exam Prep

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What are the differences between abstract classes and interfaces?

Abstract Class: Can have both abstract (unimplemented) and concrete (implemented) methods, and can have member variables. Interface: Only has abstract methods (until Java 8, which introduced default and static methods), and no member variables (except constants).

Enqueue

Adds an element to the back of the structure

Push

Adds an element to the top of the structure

Which of the following statements are true about an immutable object?

An immutable object contains no mutator methods. All properties of an immutable object must be private. The contents of an immutable object cannot be modified. A readable object type property in an immutable object must also be immutable.

What is a method associated with an individual object called?

An instance method.

What exception type does the following program throw?public class Test {public static void main(String[] args) {System.out.println(1 / 0);}}

ArithmeticException

What exception does the following program throw? public class Test { public static void main(String[] args) { int[] a = new int[5]; for (int i = 0; i <= 5; i++) { a[i] = i; } } }

ArrayIndexOutOfBounds The array a has indices 0 through 4 (5 elements). The loop tries to access index 5, which is out of bounds, thus throwing an ArrayIndexOutOfBoundsException.

finally

Contains code that always executes, regardless of whether an exception occurred

throws

Declares that a method or constructor might throw certain exceptions.

Given the class below, that represents a Circle, match its parts with their definition: public class Circle { private double radius; private String color; public Circle() { this(1.0, "red"); } public Circle(double radius) { this(radius, "red"); } public Circle(double radius, String color) { this.radius = radius; this.color = color; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double area() { return area(radius); } public static double area(double radius) { return Math.PI * radius * radius; } public double circumference() { return 2 * Math.PI * radius; } }

Immutable: None (the class allows modification of attributes) Constructor: Circle(), Circle(double radius), Circle(double radius, String color) Final attribute: None (there are no final attributes) Attribute: radius, color Class method: area(double radius) Mutator: setRadius(double radius), setColor(String color)

Which is the advantage of encapsulation?

It enables changes to the implementation without changing a class's contract and causes no consequential changes to other code.

What is the relationship between Java Exceptions and try/catch blocks?

Java exceptions are used to handle errors that occur during program execution. The try block contains code that might throw an exception, and the catch block handles the exception if it is thrown. This allows programs to continue executing instead of terminating abruptly.

What is method/constructor overloading?

Method/constructor overloading allows multiple methods or constructors in a class to have the same name but with different parameter lists (type, number, or both).

What is wrong in the following program? abstract class SuperDuperClass { public boolean superMethod() { return true; } abstract void duperMethod(); }

Nothing is wrong. The SuperDuperClass is an abstract class with one concrete method (superMethod()) and one abstract method (duperMethod()). This is allowed in Java, so there is nothing wrong with the class.

What is the class that all other classes derive from in Java?

Object

This concept allows you to treat objects of different classes in a uniform way, regardless of their specific types.

Polymorphism

Dequeue

Removes and returns the front element of the structure

Pop

Removes and returns the top element of the structure

FileNotFoundException

Represents an exception type that is thrown when a file is not found

NullPointerException

Represents an exception type that occurs when attempting to perform an operation on an object reference that hasn't been initialized

ArithmeticException

Represents an exception type that occurs when trying to perform an invalid mathematical operation

Peek

Returns the front/top element without removing it

Which class do you use to read data from a text file?

Scanner

Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { Calendar[] calendars = new Calendar[10]; calendars[0] = new Calendar(); calendars[1] = new GregorianCalendar(); } }

The program has a compile error on Line 5 because java.util.Calendar is an abstract class. Calendar is abstract and cannot be instantiated directly. The code will give a compile-time error on Line 5 where new Calendar() is attempted.

Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in);int v1 = input.nextInt();int v2 = input.nextInt();String line = input.nextLine();

The program has a runtime error because 34.3 is not an integer.

A Java exception is an instance of ________.

Throwable

A subclass cannot extend more than one class, but may implement any number of interfaces

True. Java does not support multiple inheritance for classes (a subclass cannot extend more than one class), but it allows implementing multiple interfaces.

Which of the following statements are true? - Encapsulating data fields makes the program short. - Use the private modifier to encapsulate data fields. - Encapsulating data fields helps prevent programming errors. - Encapsulating data fields makes the program easy to maintain.

Use the private modifier to encapsulate data fields.

throw

Used to explicitly throw an exception within your code.

What is list after the following code is executed?ArrayList list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.remove(2); System.out.println(list);

[1, 2, 4, 5]

An aggregation relationship is usually represented as ________ in ________.

a data field; the aggregating class

When you return an array from a method, the method returns ________.

a reference to the array

When you pass an array to a method, the method receives ________.

a reference to the array.

A class that cannot be instantiated and serves as a blueprint for other classes to extend from.

abstract class

Everything in Java is

an Object

________ represents an entity in the real world that can be distinctly identified.

an object

Once an array is created, its size ________.

cannot change

An object is an instance of a...?

class

Variables that are shared by every instance of a class are ________.

class variables

What is invoked to create an object?

constructor

Which of the following classes cannot be extended?

final class A { }

A fundamental concept that allows a class to acquire properties and behaviors from another class.

inheritance

A contract that defines a set of methods that a class must implement, promoting code reusability and multiple inheritance.

interfaces

Given the following code, find the compile error. public class Test {public static void main(String[] args) {m(new GraduateStudent());m(new Student());m(new Person());m(new Object());}public static void m(Student x) {System.out.println(x.toString());}}class GraduateStudent extends Student {}class Student extends Person {@Overridepublic String toString() {return "Student";}}class Person extends Object {@Overridepublic String toString() {return "Person";}}

m(new Person()) causes an error.

Fill in the code to complete the following method for computing factorial. Select all that apply. /** Return the factorial for a specified index */public static long factorial(int n) {if (n == 0) // Base casereturn 1;elsereturn ________; // Recursive call}

n * factorial(n - 1) factorial(n - 1) * n

Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return ________; // Recursive call }

n * factorial(n - 1) or (d) factorial(n - 1) * n. The recursive call multiplies the current number n by the factorial of n-1 until reaching the base case where n == 0.

What are the base cases in the following recursive method?public static void xMethod(int n) {if (n >= 0) {System.out.print(n % 10);xMethod(n / 10);}}

n < 0

What are the base cases in the following recursive method? public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } }

no base cases The method lacks a base case (i.e., the condition to stop recursion when n <= 0). It will recursively call itself indefinitely unless some condition is added to stop the recursion.

It allows a class to have multiple methods with the same name but different behaviors depending on the arguments.

overloading

Methods must have different parameter lists (different types or different numbers of parameters).

overloading

Refers to defining multiple methods in the same class with the same name but with different parameters.

overloading

Allows a subclass to provide its own implementation of a method.

overriding

Occurs when a subclass provides a specific implementation of a method that is already provided by its parent class.

overriding

The method signature must match the original method signature.

overriding

The ________ method in the Queue interface retrieves, but does not remove, the head of this queue, returning null if this queue is empty.

peek()

Suppose you wish to provide an accessor method for a boolean property finished, what should the signature of this method be?

public boolean isFinished()

An immutable class cannot have...?

public data fields

Create a public interface named Predator with two methods (declare in this order): the first is named "chasePrey", returns a "boolean" and expects a "Prey" object argument; the second is called "eatPrey", doesn't return anything, and also expects a "Prey" object argument.

public interface Predator { // Method to chase prey, returns a boolean and expects a Prey object as an argument boolean chasePrey(Prey prey); // Method to eat prey, doesn't return anything and expects a Prey object as an argument void eatPrey(Prey prey); }

The ________ method in the Queue interface retrieves and removes the head of this queue and throws an exception if this queue is empty.

remove() The remove() method in the Queue interface retrieves and removes the head of the queue, throwing a NoSuchElementException if the queue is empty. The poll() method, on the other hand, would return null when the queue is empty.

Inheritance means ________

that a class can extend another class

Composition means ________.

that a class contains a data field that references another object

Polymorphism means ________.

that a variable of supertype can refer to a subtype object

The signature of a method consists of ________.

the method's name and the parameter list

A subclass of a non-abstract class must be non-abstract.

true If a class is not abstract, all of its subclasses must provide concrete implementations for all of its methods, unless the subclass itself is abstract.

To prevent a class from being instantiated, ________.

use the private modifier on the constructor

Assume int[][] x = {{1, 2}, {3, 4}, {5, 6}}. What are x.length and x[0].length?

x.length = 3 x[0].length = 2

What are recursive functions? What are their parts?

A recursive function is a function that calls itself in its definition. Parts: Base case: The condition that stops recursion. Recursive case: The part where the function calls itself with modified arguments

How many times will the following code print "Welcome to Java"? int count = 0; while (count < 10) { System.out.println("Welcome to Java"); count++; }

10 times

Assume double[][][] x = new double[4][5][6]. What are x.length, x[2].length, and x[0][0].length?

4, 5, 6

What are Queues? Give an example of a situation you would use a Queue.

A Queue is a data structure that follows the FIFO (First-In-First-Out) principle. You use a queue when you need to process items in the order they were added. Example: A print queue where print jobs are processed in the order they are received.

What are Stacks? Give an example of a situation you would use a Stack.

A Stack is a data structure that follows the LIFO (Last-In-First-Out) principle. You use a stack when you need to process the most recently added item first. Example: A web browser's back button, which pops the last visited page from the stack.

________ is a template that defines objects of the same type.

A class

Which of the following is incorrect?

A constructor may be static.

What is encapsulation?

Encapsulation is the bundling of data (fields) and methods that operate on that data into a single unit or class. It also involves restricting direct access to some components (using private fields) and providing controlled access through public methods (getters and setters).

try

Encloses the code that might throw an exception.

Which of the following statements are true? Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case. A recursive method is invoked differently from a non-recursive method. Every recursive method must have a return value. Every recursive method must have a base case or a stopping condition.

Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case.

Which of the following is not an advantage of Java exception handling?

Exception handling improves performance. Exception handling does not improve performance; in fact, handling exceptions can sometimes incur performance costs. Its main purpose is to handle errors gracefully.

What does the final modifier mean for classes? What does it mean for methods?

Final class: A class marked final cannot be subclassed. Final method: A method marked final cannot be overridden by subclasses.

What are getters and setters used for?

Getters and setters are used to access and update private fields of a class while maintaining control and validation over the process.

catch

Handles specific types of exceptions that can be thrown within a try block

Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code: class Square extends GeometricObject { double length; Square(double length) { GeometricObject(length); } }

The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally.

Fibonacci

The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.


Set pelajaran terkait

Chapter 11 - How Home Ownership is Held

View Set

week 4 carmen quiz: correlation and regression

View Set

Chapter 11: Nutritional Assessment

View Set

Explorer Study Guide - John Cabot

View Set