Unit 4 - Practice Quiz

CSE310 62 Questions
0 Correct 0 Wrong 62 Left
0/62

1 A class that is defined inside another class is known as a(n)...

Nested Class Easy
A. External Class
B. Nested Class
C. Friend Class
D. Super Class

2 Which type of nested class can be instantiated without an instance of the outer class?

Understanding the importance of static and non-static nested classes Easy
A. Static nested class
B. Local class
C. Anonymous class
D. Inner class (non-static)

3 What is the primary characteristic of an anonymous class?

Local and Anonymous class Easy
A. It has no name
B. It must be declared as public
C. It cannot implement an interface
D. It can have multiple constructors

4 How many abstract methods can a functional interface have?

Functional Interface Easy
A. Any number
B. Two or more
C. Exactly one
D. Zero

5 What symbol is used to separate the parameters from the body in a Java lambda expression?

Lambda expressions Easy
A. => (fat arrow)
B. : (colon)
C. -> (arrow)
D. :: (double colon)

6 In modern Java (8+), which class from the java.time package represents a specific date without time information, like '2023-10-27'?

Utility Classes : Working with Dates Easy
A. Date
B. Instant
C. Calendar
D. LocalDate

7 What is the main goal of exception handling in Java?

Exceptions and Assertions : Exception overview Easy
A. To handle runtime errors gracefully and maintain the normal flow of the application
B. To make the program run faster
C. To stop the program immediately when any error occurs
D. To replace if-else conditional logic

8 Which class is at the top of the Java exception hierarchy?

Exception class hierarchy and exception types Easy
A. java.lang.Object
B. java.lang.Error
C. java.lang.Throwable
D. java.lang.Exception

9 What happens if an exception is thrown in a method and is not caught by any catch block within the method call stack?

Propagation of exceptions Easy
A. The exception is automatically converted to a warning
B. The compiler shows an error
C. The program terminates
D. The exception is ignored

10 In a try-catch-finally structure, which block is always executed, regardless of whether an exception occurred or not?

Using try, catch and finally for exception handling Easy
A. catch
B. try
C. The code after the structure
D. finally

11 What is the purpose of the throw keyword in Java?

Usage of throw and throws Easy
A. To catch a specific type of exception
B. To manually create and throw an exception object
C. To define a new exception class
D. To declare that a method might throw an exception

12 What is the correct syntax for catching multiple exception types in a single catch block?

handling multiple exceptions using multi-catch Easy
A. catch (IOException, SQLException ex)
B. catch (IOException & SQLException ex)
C. catch (IOException || SQLException ex)
D. catch (IOException | SQLException ex)

13 To be used in a try-with-resources statement, a resource must implement which interface?

Autoclose resources with try-with resources statement Easy
A. java.lang.Runnable
B. java.io.Serializable
C. java.lang.AutoCloseable
D. java.util.Iterable

14 To create a custom checked exception, your new class should extend...

Creating custom exceptions Easy
A. java.lang.Throwable
B. java.lang.Exception
C. java.lang.Error
D. java.lang.RuntimeException

15 Which Java keyword is used to test an assumption about the state of a program, which can be disabled in production code?

Testing invariants by using assertions Easy
A. assert
B. check
C. ensure
D. verify

16 A non-static nested class, also known as an inner class, has direct access to...

Understanding the importance of static and non-static nested classes Easy
A. all members (including private) of the enclosing class instance
B. only the static members of the enclosing class
C. only the public members of the enclosing class instance
D. no members of the enclosing class

17 A local class is a class that is defined inside a...

Local and Anonymous class Easy
A. method or code block
B. separate file
C. package
D. static initializer

18 A lambda expression in Java can be understood as a concise representation of a(n)...

Lambda expressions Easy
A. anonymous function
B. named class
C. static variable
D. constructor

19 What is the primary role of the try block?

Using try, catch and finally for exception handling Easy
A. To ensure a piece of code is always executed
B. To re-throw an exception
C. To enclose the code that might throw an exception
D. To execute code that handles an exception

20 Which of the following is an example of a common unchecked exception?

Exception class hierarchy and exception types Easy
A. NullPointerException
B. FileNotFoundException
C. SQLException
D. IOException

21 Consider the following Java code. What will be the result of compiling and running this code?

java
class Outer {
private int outerVar = 10;

static class StaticNested {
void display() {
// Line X
System.out.println("Value: " + outerVar);
}
}

public static void main(String[] args) {
Outer.StaticNested nested = new Outer.StaticNested();
nested.display();
}
}

Understanding the importance of static and non-static nested classes Medium
A. A runtime NullPointerException occurs.
B. The code compiles but throws an IllegalAccessException at runtime.
C. The code compiles and prints "Value: 10".
D. A compilation error occurs at Line X.

22 Given the Outer and Inner classes below, which of the following code snippets correctly creates an instance of the Inner class from a separate class Main?

java
// In file Outer.java
public class Outer {
public class Inner {
public void show() {
System.out.println("Inner class method.");
}
}
}

// In file Main.java
public class Main {
public static void main(String[] args) {
// How to create an instance of Inner here?
}
}

Nested Class Medium
A. Outer.Inner inner = new Outer.Inner();
B. Inner inner = new Outer.Inner();
C. Outer.Inner inner = new Outer().new Inner();
D. Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

23 What is the output of the following Java code snippet?

java
interface Greeter {
void greet();
}

public class Test {
public void sayHello() {
int count = 1;
Greeter greeter = new Greeter() {
@Override
public void greet() {
// The 'count' variable is effectively final
System.out.println("Hello count: " + count);
}
};
greeter.greet();
}

public static void main(String[] args) {
new Test().sayHello();
}
}

Local and Anonymous class Medium
A. A compilation error because 'count' is not declared final.
B. A compilation error because anonymous classes cannot access local variables.
C. Hello count: 1
D. A runtime exception.

24 Which of the following interface definitions is NOT a valid functional interface in Java?

Functional Interface Medium
A. java
interface Calculator {
int calculate(int a, int b);
int subtract(int a, int b);
}
B. java
interface Validator {
boolean validate();
static boolean isNull(Object obj) {
return obj == null;
}
}
C. java
interface Runnable {
// Inherits from Java's standard library
void run();
}
D. java
@FunctionalInterface
interface Printer {
void print(String msg);
default void log(String msg) {
// ...
}
}

25 What will be printed to the console when the following code is executed?

java
import java.util.Arrays;
import java.util.List;

public class LambdaTest {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Anna");
names.stream()
.filter(s -> s.length() > 3)
.filter(s -> s.startsWith("A"))
.forEach(System.out::println);
}
}

Lambda expressions Medium
A. Alice
B. Charlie
C. Alice
Anna
D. Alice
Charlie

26 What is the return value of the testMethod() in the following code snippet?

java
public class FinallyTest {
public static int testMethod() {
try {
System.out.println("Inside try");
return 1;
} catch (Exception e) {
return 2;
} finally {
System.out.println("Inside finally");
return 3;
}
}

public static void main(String[] args) {
System.out.println("Return value: " + testMethod());
}
}

Using try, catch and finally for exception handling Medium
A. 1
B. 2
C. 3
D. The code does not compile because a finally block cannot have a return statement.

27 Analyze the following code. What is the output?

java
class Propagate {
void methodA() {
try {
System.out.println("In method A");
methodB();
} catch (ArithmeticException e) {
System.out.println("Caught in A");
}
}

void methodB() {
System.out.println("In method B");
throw new NullPointerException();
}

public static void main(String[] args) {
try {
new Propagate().methodA();
} catch (Exception e) {
System.out.println("Caught in main");
}
System.out.println("End of main");
}
}

Propagation of exceptions Medium
A. In method A
In method B
Caught in main
End of main
B. A compilation error occurs.
C. In method A
In method B
Caught in A
End of main
D. In method A
In method B
Caught in A
Caught in main
End of main

28 Which statement is true regarding the throw and throws keywords in Java?

Usage of throw and throws Medium
A. throws is used to handle an exception, similar to a catch block, while throw is used to create a new exception.
B. throw is used in a method signature to declare exceptions, while throws is used within a method body to trigger an exception.
C. Both throw and throws are used to manually trigger an exception inside a method.
D. throws is used in a method signature to declare exceptions that might be thrown, while throw is used to actually throw an exception object.

29 You need to create a custom checked exception named InvalidAgeException. Which of the following is the correct way to define it?

Creating custom exceptions Medium
A. java
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
B. java
public class InvalidAgeException implements Throwable {
// ... implementation
}
C. java
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
D. java
public class InvalidAgeException extends Error {
public InvalidAgeException(String message) {
super(message);
}
}

30 What is the output of the following code, assuming MyResource is correctly defined?

java
class MyResource implements AutoCloseable {
public MyResource() { System.out.println("Resource created"); }
public void use() {
System.out.println("Resource used");
throw new RuntimeException("Error during use");
}
@Override
public void close() {
System.out.println("Resource closed");
}
}

public class TestResource {
public static void main(String[] args) {
try (MyResource r = new MyResource()) {
r.use();
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

Autoclose resources with try-with-resources statement Medium
A. Resource created
Resource used
Caught: Error during use
Resource closed
B. Resource created
Resource used
Resource closed
Caught: Error during use
C. Resource created
Resource used
D. Resource created
Resource used
Resource closed

31 Consider the code below. Which statement correctly describes its behavior?

java
public void processData(int mode) throws java.io.IOException, java.sql.SQLException {
if (mode == 1) {
throw new java.io.IOException("IO Error");
} else {
throw new java.sql.SQLException("SQL Error");
}
}

// In another method:
try {
processData(1);
} catch (java.io.IOException | java.sql.SQLException e) {
System.out.println(e.getMessage());
// Line X
e = new java.io.IOException();
}

handling multiple exceptions using multi-catch Medium
A. A compilation error occurs because IOException and SQLException cannot be caught in the same block.
B. The code compiles and prints "IO Error".
C. The code compiles and prints "SQL Error".
D. A compilation error occurs at Line X because the multi-catch parameter e is implicitly final.

32 A method calculates the speed of a particle, which should never be negative. The code includes an assertion to check this condition. What is the output when the following program is run with assertions enabled (using the -ea flag)?

java
public class PhysicsCalc {
public static void main(String[] args) {
double speed = calculateSpeed(-10.0);
System.out.println("Calculation finished.");
}

public static double calculateSpeed(double velocity) {
// some complex calculation results in a negative value
double result = velocity * 2;
assert result >= 0 : "Speed cannot be negative: " + result;
return result;
}
}

Testing invariants by using assertions Medium
A. The program prints an error message "Speed cannot be negative: -20.0" and exits normally.
B. The program terminates abruptly by throwing an AssertionError.
C. The program prints "Calculation finished." and exits normally.
D. A compilation error occurs because of the assert statement.

33 What is the output of the following Java code that uses the java.time API?

java
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class DateTest {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2023, Month.JANUARY, 30);
LocalDate endDate = startDate.plus(1, ChronoUnit.MONTHS);
System.out.println(endDate);
}
}

Utility Classes : Working with Dates Medium
A. 2023-02-28
B. A DateTimeException is thrown at runtime.
C. 2023-03-02
D. 2023-03-01

34 A method needs to handle potential FileNotFoundException and SocketException, both of which are subclasses of IOException. Which catch block ordering is valid and follows best practices?

Exception class hierarchy and exception types Medium
A. java
try { ... }
catch (IOException e) { ... }
catch (FileNotFoundException e) { ... }
B. java
try { ... }
catch (FileNotFoundException e) { ... }
catch (SocketException e) { ... }
catch (IOException e) { ... }
C. java
try { ... }
catch (Throwable t) { ... }
catch (FileNotFoundException e) { ... }
D. java
try { ... }
catch (Exception e) { ... }
catch (IOException e) { ... }

35 What happens if an exception is thrown inside a finally block?

java
public void test() {
try {
System.out.println("Try block");
throw new IllegalArgumentException("From try");
} finally {
System.out.println("Finally block");
throw new IllegalStateException("From finally");
}
}

Using try, catch and finally for exception handling Medium
A. The exception from the try block (IllegalArgumentException) is propagated, and the exception from the finally block is ignored.
B. Both exceptions are propagated up the call stack.
C. The code results in a compilation error.
D. The exception from the finally block (IllegalStateException) is propagated, and the original exception from the try block is suppressed.

36 Given the functional interface Operator, which of the following is a valid way to call the calculate method using a lambda expression?

java
@FunctionalInterface
interface Operator {
int operate(int x, int y);
}

class Calculator {
public void calculate(Operator op) {
int result = op.operate(10, 5);
System.out.println(result);
}
}

Lambda expressions Medium
A. new Calculator().calculate((a, b) -> { a * b; });
B. new Calculator().calculate(int a, int b -> a * b);
C. new Calculator().calculate((a, b) -> a * b);
D. new Calculator().calculate({(a, b) -> a * b});

37 A method defines a local class. Which statement accurately describes the limitations and capabilities of this local class?

Local and Anonymous class Medium
A. It is allowed to contain static initializers and methods.
B. It can access local variables of the enclosing method only if they are declared final or are effectively final.
C. It can be instantiated from outside the method in which it is defined.
D. It can be declared public, private, or protected.

38 In which scenario would a static nested class be a more appropriate choice than a non-static inner class?

Understanding the importance of static and non-static nested classes Medium
A. When the nested class is used to implement an event listener that needs to update the state of the outer class instance.
B. When the nested class needs to be a helper class for the outer class but does not need access to the outer class's instance members.
C. When you want to ensure that for every instance of the outer class, there is a unique corresponding instance of the nested class.
D. When the nested class's primary purpose is to access and modify the private instance variables of the outer class.

39 What is the result of compiling and running the following code?

java
import java.io.IOException;

public class ThrowsTest {
public static void main(String[] args) {
try {
doSomething();
} catch (IOException e) {
System.out.println("Caught in main");
}
}

public static void doSomething() throws IOException {
// This method does not actually throw an exception
System.out.println("Method executed");
}
}

Usage of throw and throws Medium
A. A compilation error occurs in main because doSomething() might throw an unhandled exception.
B. The code compiles and prints "Method executed".
C. A compilation error occurs because doSomething() declares throws IOException but doesn't throw it.
D. The code compiles and prints "Method executed" followed by "Caught in main".

40 A method processPayment throws a custom checked exception InsufficientFundsException. How must the calling method makePurchase be written to compile successfully?

java
// Definition of the custom exception
class InsufficientFundsException extends Exception { ... }

class PaymentGateway {
void processPayment(double amount) throws InsufficientFundsException {
// ... logic that might throw the exception
}
}

class Store {
// How to implement this method?
void makePurchase() {
new PaymentGateway().processPayment(100.0);
}
}

Creating custom exceptions Medium
A. Both A and C are valid options.
B. java
void makePurchase() throws Exception {
new PaymentGateway().processPayment(100.0);
}
C. java
void makePurchase() {
try {
new PaymentGateway().processPayment(100.0);
} catch (InsufficientFundsException e) {
// handle exception
}
}
D. java
void makePurchase() {
new PaymentGateway().processPayment(100.0);
}

41 Consider the following code. What is the output when this code is compiled and run?

Understanding the importance of static and non-static nested classes Hard
A. 10, 25, 30
B. Compilation Fails
C. A NullPointerException is thrown at runtime.
D. 10, 20, 30

42 Analyze the following code snippet. What will be the result of compiling and running it?

Local and Anonymous class Hard
A. The code compiles but throws a NullPointerException at runtime.
B. The code compiles and prints Result: 15.
C. The code compiles and prints Result: 10.
D. Compilation fails because z is not declared final or effectively final.

43 Given the following two functional interfaces and a class with an overloaded method, what is the result of compiling and executing the main method?

Lambda expressions
A. The code fails to compile due to an ambiguous method call.
B. The code compiles and prints Processor executed.
C. The code compiles and prints Executor executed.
D. A ClassCastException is thrown at runtime.

44 What is the output of the calculate() method when it's called from main?

Using try, catch and finally for exception handling Hard
A. Try block executed. Finally block executed. Value: 30
B. Finally block executed. Value: 30
C. The method returns 10, and "Finally block executed." is printed.
D. Try block executed. Finally block executed. Value: 10

45 Consider a resource class where both the action within the try block and the close() method throw exceptions. What is the output of the following program?

Autoclose resources with try-with-resources statement Hard
A. Caught main exception: Action Error. Suppressed: Close Error
B. A RuntimeException with the message "Action Error" is thrown, and the program terminates.
C. Caught main exception: Close Error. Suppressed: Action Error
D. Only "Caught main exception: Action Error" is printed.

46 Given the class hierarchy class A { public void process() throws java.io.IOException { ... } }, which of the following B class definitions is a VALID override of the process() method?

Usage of throw and throws Hard
A. java
class B extends A {
@Override
public void process() throws Exception {}
}
B. java
class B extends A {
@Override
public void process() throws java.sql.SQLException {}
}
C. java
class B extends A {
@Override
public void process() throws Throwable {}
}
D. java
class B extends A {
@Override
public void process() throws java.io.FileNotFoundException {}
}

47 Which of the following interface definitions is a valid functional interface that will compile successfully with the @FunctionalInterface annotation?

Functional Interface Hard
A. java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
default int subtract(int x, int y) { return x - y; }
boolean equals(Object obj);
}
B. java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
static int add(int x, int y) { return x + y; }
}
C. java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
String toString();
}
D. java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
int anotherCalculate(int x, int y);
}

48 Which of the following interface definitions is a valid functional interface that will compile successfully with the @FunctionalInterface annotation?

Functional Interface Hard
A. java
@FunctionalInterface
interface Computable {
void compute();
// Cannot reduce visibility of the inherited public method
protected String toString();
}
B. java
@FunctionalInterface
interface Computable {
void compute();
void log();
}
C. java
@FunctionalInterface
interface Computable {
// No abstract method declared
default void log() { System.out.println("Logging"); }
}
D. java
@FunctionalInterface
interface Computable {
void compute();
boolean equals(Object obj);
static void log() { System.out.println("Logging"); }
}

49 You are designing an API where a network operation can fail due to a transient, recoverable issue (e.g., temporary network glitch). The caller should be forced to handle this possibility. Which is the most appropriate custom exception design for this scenario?

Creating custom exceptions Hard
A. java
class TransientNetworkException extends RuntimeException { ... }
B. java
class TransientNetworkException extends Exception { ... }
C. java
class TransientNetworkException extends java.io.IOException { ... }
D. java
class TransientNetworkException extends Error { ... }

50 What is the output of the following code when compiled and run with the command java -ea Main?

Testing invariants by using assertions Hard
A. x before assertion: 10
B. x before assertion: 10\nx after assertion: 11
C. An AssertionError is thrown.
D. x before assertion: 10\nx after assertion: 10

51 What is the output of the following code when compiled and run with assertions enabled (java -ea Main)?

Testing invariants by using assertions Hard
A. x before assertion: 10\nx after assertion: 11
B. The program fails to compile.
C. The program terminates with an AssertionError.
D. x before assertion: 10\nx after assertion: 10

52 Analyze the following exception propagation chain. What is the final output printed to the console?

Propagation of exceptions Hard
A. Caught in B: Original
B. Caught in B: Original\nFinally in B\nCaught in A: Transformed
C. Caught in B: Original\nCaught in A: Transformed
D. Caught in B: Original\nFinally in B\nProgram terminates due to an unhandled exception.

53 Why does the following Java code snippet fail to compile?

Handling multiple exceptions using multi-catch Hard
A. In a multi-catch block, one exception type cannot be a subclass of another exception type listed in the same block.
B. A multi-catch block requires a finally block to be present.
C. The variable e in a multi-catch block is implicitly final and cannot be used to call methods like getMessage().
D. The multi-catch statement cannot be used with custom exceptions.

54 You are running the following code in a region that observes Daylight Saving Time (DST), such as America/New_York. The DST 'spring forward' occurs on March 10, 2024, at 2:00 AM, when clocks jump to 3:00 AM. What will be the output?

Utility Classes : Working with Dates Hard
A. 2024-03-10T02:30-04:00[America/New_York]
B. 2024-03-10T02:30-05:00[America/New_York]
C. 2024-03-10T03:30-04:00[America/New_York]
D. An IllegalArgumentException is thrown.

55 What is the behavior of the following code when executed?

Exception class hierarchy and exception types Hard
A. The program will enter an infinite loop and eventually crash without printing anything.
B. The program will print "Caught Error" and then "Finished".
C. The program will print "Finally" and then terminate by throwing a StackOverflowError.
D. The program will print "Caught Error", "Finally", and then "Finished".

56 What is printed to the console when the main method of the Test class is executed?

Local and Anonymous class Hard
A. Compilation Fails.
B. Anonymous says: 11
C. A NullPointerException is thrown.
D. Anonymous says: 10

57 Analyze the following nested class structure. What is the output of this program?

Nested Class Hard
A. Accessing: Outer.s_var, null, Local.l_var
B. Accessing: Outer.s_var, Inner.i_var, Local.l_var
C. Compilation Fails.
D. A NullPointerException is thrown at runtime.

58 What is the output when the run method is executed, given the following Resource classes?

Autoclose resources with try-with-resources statement Hard
A. Creating R1\nCreating R2\nRunning...\nClosing R2\nClosing R1
B. Creating R1\nCreating R2\nRunning...\nClosing R1\nClosing R2
C. Creating R2\nCreating R1\nRunning...\nClosing R1\nClosing R2
D. Creating R2\nCreating R1\nRunning...\nClosing R2\nClosing R1

59 Consider the following code that attempts to create a recursive factorial function using a lambda expression. What is the result of compiling and running this code?

Lambda expressions Hard
A. The code compiles and prints 120.
B. The code compiles but throws a StackOverflowError at runtime.
C. The code fails to compile because the variable factorial is not initialized when it is used inside the lambda.
D. The code fails to compile because a lambda expression cannot be recursive.

60 An instance of a non-static inner class Inner is created. If the instance of the enclosing class Outer becomes eligible for garbage collection, but a strong reference to the Inner instance is maintained, what happens?

Understanding the importance of static and non-static nested classes Hard
A. The Outer instance will not be garbage collected because the Inner instance holds an implicit reference to it.
B. Both the Outer and Inner instances will be garbage collected together.
C. This scenario causes a compilation error because an Inner instance cannot outlive its Outer instance.
D. The Outer instance will be garbage collected, and the Inner instance will remain, but trying to access outer members will throw a NullPointerException.

61 What is the result of executing the main method in the provided code snippet?

Usage of throw and throws Hard
A. The program prints Level 2 and Level 1 and terminates normally.
B. The program prints Level 2 and Level 1 and then terminates with an uncaught SQLException.
C. The code fails to compile.
D. The program prints Level 2 and then terminates with an uncaught SQLException.

62 Analyze the following custom exception class. What is a significant flaw in its design according to Java best practices?

Creating custom exceptions Hard
A. A custom exception cannot have more than one constructor.
B. The constructor should not accept a Throwable cause.
C. It extends Exception, making it a checked exception, but its name (InvalidStateException) implies a programming error that should be unchecked.
D. The exception class should be final to prevent further subclassing.