1A class that is defined inside another class is known as a(n)...
Nested Class
Easy
A.Super Class
B.External Class
C.Nested Class
D.Friend Class
Correct Answer: Nested Class
Explanation:
By definition, a class that is declared inside another class or interface is called a nested class. This is done to group classes that are only used in one place, which increases encapsulation.
Incorrect! Try again.
2Which 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.Local class
B.Inner class (non-static)
C.Static nested class
D.Anonymous class
Correct Answer: Static nested class
Explanation:
A static nested class is associated with its outer class, not an instance. Therefore, you can create an object of a static nested class without first creating an object of the outer class.
Incorrect! Try again.
3What is the primary characteristic of an anonymous class?
Local and Anonymous class
Easy
A.It can have multiple constructors
B.It cannot implement an interface
C.It has no name
D.It must be declared as public
Correct Answer: It has no name
Explanation:
An anonymous class is an inner class without a name. Since it has no name, it is both declared and instantiated in a single expression, typically used for creating a one-time-use object.
Incorrect! Try again.
4How many abstract methods can a functional interface have?
Functional Interface
Easy
A.Zero
B.Exactly one
C.Any number
D.Two or more
Correct Answer: Exactly one
Explanation:
A functional interface in Java is an interface that contains exactly one abstract method. This is a requirement for it to be the target of a lambda expression. The @FunctionalInterface annotation can be used to enforce this rule.
Incorrect! Try again.
5What symbol is used to separate the parameters from the body in a Java lambda expression?
Lambda expressions
Easy
A.=> (fat arrow)
B.: (colon)
C.:: (double colon)
D.-> (arrow)
Correct Answer: -> (arrow)
Explanation:
The basic syntax of a lambda expression consists of a parameter list, the arrow token ->, and a body. For example: (parameter) -> { body }.
Incorrect! Try again.
6In 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.LocalDate
B.Date
C.Instant
D.Calendar
Correct Answer: LocalDate
Explanation:
java.time.LocalDate is the modern, immutable class for representing a date without time-of-day or timezone information. The older java.util.Date and java.util.Calendar classes are now largely considered legacy.
Incorrect! Try again.
7What is the main goal of exception handling in Java?
Exceptions and Assertions : Exception overview
Easy
A.To replace if-else conditional logic
B.To make the program run faster
C.To stop the program immediately when any error occurs
D.To handle runtime errors gracefully and maintain the normal flow of the application
Correct Answer: To handle runtime errors gracefully and maintain the normal flow of the application
Explanation:
Exception handling allows a program to deal with unexpected situations (errors) in a controlled way, preventing an abrupt crash and enabling recovery or graceful termination.
Incorrect! Try again.
8Which class is at the top of the Java exception hierarchy?
Exception class hierarchy and exception types
Easy
A.java.lang.Throwable
B.java.lang.Error
C.java.lang.Exception
D.java.lang.Object
Correct Answer: java.lang.Throwable
Explanation:
The Throwable class is the superclass of all errors and exceptions in Java. Its two main subclasses are Error (for severe system issues) and Exception (for conditions that applications might want to catch).
Incorrect! Try again.
9What 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 program terminates
C.The compiler shows an error
D.The exception is ignored
Correct Answer: The program terminates
Explanation:
If an exception propagates all the way up the call stack without being caught, it reaches the Java Virtual Machine (JVM), which will terminate the program and typically print a stack trace.
Incorrect! Try again.
10In 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.finally
B.The code after the structure
C.catch
D.try
Correct Answer: finally
Explanation:
The finally block is designed to contain cleanup code (like closing files or database connections) that must run no matter what happens in the try block, ensuring resources are released properly.
Incorrect! Try again.
11What is the purpose of the throw keyword in Java?
Usage of throw and throws
Easy
A.To declare that a method might throw an exception
B.To catch a specific type of exception
C.To manually create and throw an exception object
D.To define a new exception class
Correct Answer: To manually create and throw an exception object
Explanation:
The throw keyword is used within a method body to explicitly throw an instance of an exception. In contrast, the throws keyword is used in a method signature to declare exceptions that the method might propagate.
Incorrect! Try again.
12What is the correct syntax for catching multiple exception types in a single catch block?
handling multiple exceptions using multi-catch
Easy
The multi-catch feature, introduced in Java 7, uses a single vertical bar | to separate the different exception types that the catch block can handle.
Incorrect! Try again.
13To 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.AutoCloseable
B.java.io.Serializable
C.java.lang.Runnable
D.java.util.Iterable
Correct Answer: java.lang.AutoCloseable
Explanation:
The try-with-resources statement automatically calls the close() method on any resource declared in its parentheses. This is possible only for classes that implement the AutoCloseable interface (or its subinterface Closeable).
Incorrect! Try again.
14To create a custom checked exception, your new class should extend...
Creating custom exceptions
Easy
A.java.lang.RuntimeException
B.java.lang.Error
C.java.lang.Throwable
D.java.lang.Exception
Correct Answer: java.lang.Exception
Explanation:
Checked exceptions are those that the compiler forces you to handle. To create one, you must extend the java.lang.Exception class or one of its subclasses (that is not RuntimeException).
Incorrect! Try again.
15Which 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.verify
B.assert
C.ensure
D.check
Correct Answer: assert
Explanation:
The assert keyword is used to declare an assertion. It checks if a boolean condition is true and throws an AssertionError if it is false. Assertions are primarily for debugging and are disabled by default.
Incorrect! Try again.
16A 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.only the static members of the enclosing class
B.only the public members of the enclosing class instance
C.all members (including private) of the enclosing class instance
D.no members of the enclosing class
Correct Answer: all members (including private) of the enclosing class instance
Explanation:
A key feature of an inner class (non-static nested class) is that it is associated with an instance of its outer class and can access all of that instance's fields and methods, even the private ones.
Incorrect! Try again.
17A local class is a class that is defined inside a...
Local and Anonymous class
Easy
A.separate file
B.package
C.method or code block
D.static initializer
Correct Answer: method or code block
Explanation:
Local classes are defined within the scope of a block, typically a method body. They are not visible outside of that block and can be useful for very localized, specific tasks.
Incorrect! Try again.
18A lambda expression in Java can be understood as a concise representation of a(n)...
Lambda expressions
Easy
A.static variable
B.anonymous function
C.constructor
D.named class
Correct Answer: anonymous function
Explanation:
Lambda expressions are essentially anonymous functions—blocks of code with parameters—that can be treated as a value. They provide a clear and compact way to implement a method of a functional interface.
Incorrect! Try again.
19What is the primary role of the try block?
Using try, catch and finally for exception handling
Easy
A.To enclose the code that might throw an exception
B.To execute code that handles an exception
C.To re-throw an exception
D.To ensure a piece of code is always executed
Correct Answer: To enclose the code that might throw an exception
Explanation:
The try block is used to surround the segment of code where an exception might occur. If an exception is thrown within this block, the JVM looks for a corresponding catch block to handle it.
Incorrect! Try again.
20Which of the following is an example of a common unchecked exception?
Exception class hierarchy and exception types
Easy
A.SQLException
B.IOException
C.FileNotFoundException
D.NullPointerException
Correct Answer: NullPointerException
Explanation:
Unchecked exceptions (subclasses of RuntimeException) represent programming errors that are typically not expected to be recovered from, like trying to access a method on a null reference. IOException and SQLException are examples of checked exceptions, which must be handled.
Incorrect! Try again.
21Consider 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.The code compiles and prints "Value: 10".
B.The code compiles but throws an IllegalAccessException at runtime.
C.A compilation error occurs at Line X.
D.A runtime NullPointerException occurs.
Correct Answer: A compilation error occurs at Line X.
Explanation:
A static nested class does not have access to the non-static (instance) members of its outer class. The outerVar is an instance variable, so the static class StaticNested cannot access it directly. This will result in a compilation error stating 'non-static variable outerVar cannot be referenced from a static context'.
Incorrect! Try again.
22Given 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.Inner inner = new Outer.Inner();
B.Outer.Inner inner = new Outer().new Inner();
C.Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
A non-static nested class (or inner class) is associated with an instance of its outer class. To create an instance of the inner class, you must first have an instance of the outer class. The correct syntax is outerInstance.new InnerClassName().
Incorrect! Try again.
23What 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.Hello count: 1
B.A compilation error because anonymous classes cannot access local variables.
C.A compilation error because 'count' is not declared final.
D.A runtime exception.
Correct Answer: Hello count: 1
Explanation:
Starting from Java 8, a local or anonymous class can access local variables of the enclosing scope that are effectively final. An effectively final variable is one whose value is never changed after it is initialized. Since count is initialized to 1 and never modified, it is effectively final and can be accessed by the anonymous Greeter implementation. Therefore, the code compiles and runs successfully.
Incorrect! Try again.
24Which of the following interface definitions is NOT a valid functional interface in Java?
Functional Interface
Medium
A.java
interface Runnable {
// Inherits from Java's standard library
void run();
}
Correct Answer: java
interface Calculator {
int calculate(int a, int b);
int subtract(int a, int b);
}
Explanation:
A functional interface must have exactly one abstract method. The Calculator interface declares two abstract methods (calculate and subtract), so it is not a functional interface. The other options are valid: Printer has one abstract method and a default method. Validator has one abstract method and a static method. Runnable has only one abstract method, run().
Incorrect! Try again.
25What will be printed to the console when the following code is executed?
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
Anna
B.Charlie
C.Alice
D.Alice
Charlie
Correct Answer: Alice
Explanation:
The code processes a list of names. The first filter s -> s.length() > 3 keeps elements with more than 3 characters: ["Alice", "Charlie"]. The second filter s -> s.startsWith("A") is applied to this reduced stream, which only keeps elements starting with 'A'. From ["Alice", "Charlie"], only "Alice" satisfies this condition. Therefore, "Alice" is the only name printed.
Incorrect! Try again.
26What 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;
}
}
Using try, catch and finally for exception handling
Medium
A.The code does not compile because a finally block cannot have a return statement.
B.3
C.2
D.1
Correct Answer: 3
Explanation:
The finally block is always executed after the try block, regardless of whether an exception occurred. If both the try (or catch) block and the finally block have return statements, the value returned from the finally block will override the value from the try/catch block. Here, the try block prepares to return 1, but then the finally block executes and returns 3, which becomes the final return value of the method.
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.A compilation error occurs.
B.In method A
In method B
Caught in A
Caught in main
End of main
C.In method A
In method B
Caught in A
End of main
D.In method A
In method B
Caught in main
End of main
Correct Answer: In method A
In method B
Caught in main
End of main
Explanation:
methodB throws a NullPointerException. This exception propagates to its caller, methodA. The catch block in methodA only catches ArithmeticException, so it cannot handle the NullPointerException. The exception continues to propagate up to main. The catch block in main catches Exception (which is a superclass of NullPointerException), so it handles the exception. The program flow is: print "In method A", print "In method B", exception thrown, print "Caught in main", and finally print "End of main".
Incorrect! Try again.
28Which statement is true regarding the throw and throws keywords in Java?
Usage of throw and throws
Medium
A.Both throw and throws are used to manually trigger an exception inside a method.
B.throws is used in a method signature to declare exceptions that might be thrown, while throw is used to actually throw an exception object.
C.throw is used in a method signature to declare exceptions, while throws is used within a method body to trigger an exception.
D.throws is used to handle an exception, similar to a catch block, while throw is used to create a new exception.
Correct Answer: throws is used in a method signature to declare exceptions that might be thrown, while throw is used to actually throw an exception object.
Explanation:
The throws keyword is a declaration used in a method's signature to indicate to the caller that the method might throw one of the listed checked exceptions. The caller must then handle or propagate it. The throw keyword is an action used inside a method body to explicitly create and throw an exception object, causing an immediate halt in normal program flow.
Incorrect! Try again.
29You 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 implements Throwable {
// ... implementation
}
B.java
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
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);
}
}
Correct Answer: java
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
Explanation:
In Java, custom exceptions are created by extending an existing exception class. To create a checked exception, which the compiler forces you to handle, you should extend the java.lang.Exception class. Extending RuntimeException creates an unchecked exception. Extending Error is reserved for serious system-level problems and is not recommended for application-level exceptions.
Incorrect! Try again.
30What 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
Resource closed
Caught: Error during use
B.Resource created
Resource used
Resource closed
C.Resource created
Resource used
Caught: Error during use
Resource closed
D.Resource created
Resource used
Correct Answer: Resource created
Resource used
Resource closed
Caught: Error during use
Explanation:
In a try-with-resources statement, the resource is initialized first ("Resource created"). Then, the try block is executed. Inside r.use(), "Resource used" is printed, and a RuntimeException is thrown. Before the exception is passed to the catch block, the finally block implicitly created by the try-with-resources statement is executed, which calls the close() method ("Resource closed"). Finally, the catch block executes and prints the exception message.
Incorrect! Try again.
31Consider 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.The code compiles and prints "SQL Error".
B.A compilation error occurs at Line X because the multi-catch parameter e is implicitly final.
C.A compilation error occurs because IOException and SQLException cannot be caught in the same block.
D.The code compiles and prints "IO Error".
Correct Answer: A compilation error occurs at Line X because the multi-catch parameter e is implicitly final.
Explanation:
The multi-catch syntax catch (Type1 | Type2 e) is a convenient way to handle multiple exception types with the same code block. A key rule for this feature is that the exception parameter (e in this case) is implicitly final. This means you cannot reassign it a new value within the catch block. Attempting to do so, as shown on Line X, results in a compilation error.
Incorrect! Try again.
32A 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 terminates abruptly by throwing an AssertionError.
B.A compilation error occurs because of the assert statement.
C.The program prints an error message "Speed cannot be negative: -20.0" and exits normally.
D.The program prints "Calculation finished." and exits normally.
Correct Answer: The program terminates abruptly by throwing an AssertionError.
Explanation:
When assertions are enabled with the -ea (enable assertions) VM argument, the assert statement is executed. In this case, result is -20.0, so the condition result >= 0 is false. This causes an AssertionError to be thrown, with the provided message included. The program terminates at that point, and "Calculation finished." is never printed.
Incorrect! Try again.
33What is the output of the following Java code that uses the java.time API?
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-03-02
B.2023-03-01
C.A DateTimeException is thrown at runtime.
D.2023-02-28
Correct Answer: 2023-02-28
Explanation:
The java.time API is designed to handle date arithmetic intelligently. When adding one month to January 30th, the API recognizes that February 2023 does not have 30 days. Instead of throwing an error or rolling over into the next month, it adjusts the date to the last valid day of the target month, which is February 28th, 2023.
Incorrect! Try again.
34A 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
When catching multiple exceptions, the catch blocks must be ordered from the most specific subclass to the most general superclass. If a superclass (IOException) is caught before a subclass (FileNotFoundException), the subclass's catch block would become unreachable code, resulting in a compilation error. The correct approach is to catch the more specific exceptions first, followed by their parent class.
Incorrect! Try again.
35What 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 code results in a compilation error.
B.The exception from the try block (IllegalArgumentException) is propagated, and the exception from the finally block is ignored.
C.Both exceptions are propagated up the call stack.
D.The exception from the finally block (IllegalStateException) is propagated, and the original exception from the try block is suppressed.
Correct Answer: The exception from the finally block (IllegalStateException) is propagated, and the original exception from the try block is suppressed.
Explanation:
If an exception is thrown in the try block and another exception is thrown in the finally block, the exception from the finally block is the one that gets propagated up the call stack. The original exception from the try block is 'suppressed' and attached to the new exception. This ensures that the finally block's critical cleanup code can signal its own failure, which might be more important than the original error.
Incorrect! Try again.
36Given 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(int a, int b -> a * b);
B.new Calculator().calculate({(a, b) -> a * b});
C.new Calculator().calculate((a, b) -> { a * b; });
D.new Calculator().calculate((a, b) -> a * b);
Correct Answer: new Calculator().calculate((a, b) -> a * b);
Explanation:
The calculate method expects an object of type Operator. A lambda expression can be used to provide an implementation for the operate method on the fly. The expression (a, b) -> a * b matches the signature int operate(int x, int y). The types of a and b are inferred by the compiler. Option B has incorrect syntax for parameter types. Option C has a block body but is missing the return keyword. Option D has incorrect overall syntax.
Incorrect! Try again.
37A 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 be instantiated from outside the method in which it is defined.
C.It can be declared public, private, or protected.
D.It can access local variables of the enclosing method only if they are declared final or are effectively final.
Correct Answer: It can access local variables of the enclosing method only if they are declared final or are effectively final.
Explanation:
A local class is defined within a method block. Its scope is limited to that block. It cannot have access modifiers like public or private. It cannot have static members (unless they are constant variables). Crucially, for data consistency, it can only access the local variables of its enclosing method if those variables are not modified after initialization (i.e., they are final or effectively final).
Incorrect! Try again.
38In 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's primary purpose is to access and modify the private instance variables of the outer class.
C.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.
D.When you want to ensure that for every instance of the outer class, there is a unique corresponding instance of the nested class.
Correct Answer: 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.
Explanation:
A static nested class is essentially a regular class that has been nested inside another for packaging convenience. It does not have an implicit reference to an instance of the outer class, which makes it more memory-efficient. It's the ideal choice for a helper class that is logically grouped with the outer class but operates independently of any specific instance of it. Non-static inner classes are used when the nested class needs to be tightly coupled with an instance of the outer class.
Incorrect! Try again.
39What 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.The code compiles and prints "Method executed" followed by "Caught in main".
B.The code compiles and prints "Method executed".
C.A compilation error occurs in main because doSomething() might throw an unhandled exception.
D.A compilation error occurs because doSomething() declares throws IOException but doesn't throw it.
Correct Answer: The code compiles and prints "Method executed".
Explanation:
A method is allowed to declare that it throws a checked exception even if its current implementation does not actually throw one. The throws clause is part of the method's contract, warning callers that a future version of this method might throw that exception. The caller (main method) correctly handles this possibility with a try-catch block. Since no exception is actually thrown, the catch block is not executed.
Incorrect! Try again.
40A 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);
}
}
C.java
void makePurchase() throws Exception {
new PaymentGateway().processPayment(100.0);
}
D.java
void makePurchase() {
new PaymentGateway().processPayment(100.0);
}
Correct Answer: Both A and C are valid options.
Explanation:
When a method calls another method that declares a checked exception in its throws clause, the calling method has two options to satisfy the compiler. Option A: It can handle the exception immediately using a try-catch block. Option C: It can propagate the exception by declaring it in its own throws clause, making its own caller responsible for handling it. Option B is incorrect because it neither handles nor declares the checked exception, leading to a compilation error.
Incorrect! Try again.
41Consider 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.Compilation Fails
B.10, 20, 30
C.10, 25, 30
D.A NullPointerException is thrown at runtime.
Correct Answer: 10, 25, 30
Explanation:
The code compiles and runs successfully. The key is understanding variable shadowing and access rules. Inside the Inner class's display method: x refers to the Inner class's instance variable (value 30). this.x is the same. Outer.this.x explicitly refers to the Outer class's instance variable (value 20), which is then updated to 25. Outer.y refers to the Outer class's static variable (value 10). A non-static inner class holds an implicit reference to its enclosing instance, allowing it to access and modify even private members of the outer class, which is demonstrated by Outer.this.x = 25.
Incorrect! Try again.
42Analyze the following code snippet. What will be the result of compiling and running it?
Local and Anonymous class
Hard
A.The code compiles and prints Result: 15.
B.The code compiles and prints Result: 10.
C.Compilation fails because z is not declared final or effectively final.
D.The code compiles but throws a NullPointerException at runtime.
Correct Answer: Compilation fails because z is not declared final or effectively final.
Explanation:
A local or anonymous class can only access local variables of the enclosing scope that are final or effectively final. A variable is effectively final if its value is not changed after initialization. In this code, the variable z is modified (z++) after the anonymous Runnable is defined. This modification violates the effectively final rule, causing a compilation error. The compiler needs to be sure that the value of z captured by the anonymous class will not change.
Incorrect! Try again.
43Given 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.A ClassCastException is thrown at runtime.
B.The code compiles and prints Processor executed.
C.The code compiles and prints Executor executed.
D.The code fails to compile due to an ambiguous method call.
Correct Answer: The code fails to compile due to an ambiguous method call.
Explanation:
The lambda expression () -> {} is a valid implementation for both the Processor and Executor functional interfaces, as both define a single abstract method that takes no arguments and returns void. When test.execute(...) is called, the compiler cannot determine which of the two overloaded execute methods to invoke because the lambda is a compatible target type for both. This ambiguity results in a compilation error. To resolve this, the lambda would need to be explicitly cast, e.g., test.execute((Processor) () -> {});.
Incorrect! Try again.
44What is the output of the calculate() method when it's called from main?
Using try, catch and finally for exception handling
Hard
This question tests the precedence of return statements within try-catch-finally blocks.
The try block executes and sets value to 10. It then encounters a return statement.
Before the method can actually return 10, the finally block must execute.
Inside finally, the value is changed to 30, and another return statement is encountered.
A return statement in a finally block will always override any return from the corresponding try or catch block. Therefore, the method terminates and returns the value from the finally block, which is 30. The output reflects the print statement from finally and the final returned value.
Incorrect! Try again.
45Consider 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: Close Error. Suppressed: Action Error
B.A RuntimeException with the message "Action Error" is thrown, and the program terminates.
C.Caught main exception: Action Error. Suppressed: Close Error
D.Only "Caught main exception: Action Error" is printed.
Correct Answer: Caught main exception: Action Error. Suppressed: Close Error
Explanation:
In a try-with-resources statement, if an exception is thrown in the try block and another exception is thrown when close() is called, the exception from the try block is the primary one that is propagated. The exception from the close() method is suppressed and attached to the primary exception. In this case, resource.action() throws the first RuntimeException ("Action Error"). When the try block completes (abruptly), the close() method is called, which throws a second RuntimeException ("Close Error"). The catch block catches the primary exception. The suppressed exception can be retrieved by calling e.getSuppressed(), which reveals the exception from close().
Incorrect! Try again.
46Given 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 java.sql.SQLException {}
}
B.java
class B extends A {
@Override
public void process() throws Exception {}
}
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 {}
}
Correct Answer: java
class B extends A {
@Override
public void process() throws java.io.FileNotFoundException {}
}
Explanation:
The rules for overriding a method with a throws clause for checked exceptions are strict. The overriding method can:
Not declare any checked exception.
Declare the same checked exception as the superclass method.
Declare a subclass of the checked exception declared in the superclass method.
It cannot declare a broader (superclass) exception or a new checked exception that is not in the same hierarchy. FileNotFoundException is a subclass of IOException, so it is a valid, more specific exception to throw. Exception and Throwable are superclasses (broader), and SQLException is an unrelated checked exception, making them all invalid overrides.
Incorrect! Try again.
47Which 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);
String toString();
}
B.java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
default int subtract(int x, int y) { return x - y; }
boolean equals(Object obj);
}
C.java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
static int add(int x, int y) { return x + y; }
}
D.java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
int anotherCalculate(int x, int y);
}
Correct Answer: java
@FunctionalInterface
interface Calculator {
int calculate(int x, int y);
static int add(int x, int y) { return x + y; }
}
Explanation:
A functional interface must have exactly one abstract method. However
Incorrect! Try again.
48Which of the following interface definitions is a valid functional interface that will compile successfully with the @FunctionalInterface annotation?
A functional interface must contain exactly one abstract method.
Option A is incorrect because it declares two abstract methods (compute and log).
Option B is incorrect because it declares zero abstract methods; it only has a default method.
Option C is incorrect because interface methods are implicitly public. Attempting to redeclare toString (which is public in Object) with protected visibility is a compilation error.
Option D is correct. It has one abstract method, compute(). The equals(Object obj) method does not count because it is an abstract method from java.lang.Object. Static methods like log() also do not count towards the single abstract method rule. Therefore, it satisfies the criteria for a functional interface.
Incorrect! Try again.
49You 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 Error { ... }
C.java
class TransientNetworkException extends java.io.IOException { ... }
D.java
class TransientNetworkException extends Exception { ... }
Correct Answer: java
class TransientNetworkException extends Exception { ... }
Explanation:
The key requirements are that the issue is recoverable and the caller must be forced to handle it.
Extending RuntimeException (Option A) creates an unchecked exception. The compiler does not force the caller to handle it, which is against the requirement.
Extending Error (Option D) is incorrect. Errors are for critical, unrecoverable problems in the JVM itself (like OutOfMemoryError), not for application-level issues.
Extending IOException (Option C) might seem plausible, but it's overly specific. The problem is a transient API issue, which might not be strictly I/O related (e.g., a rate limit error). It's better to create a more specific exception type for your application's domain.
Extending Exception (Option B) creates a checked exception. This forces the API caller to either catch the exception or declare it in a throws clause, perfectly matching the requirement that the caller must handle this recoverable condition.
Incorrect! Try again.
50What is the output of the following code when compiled and run with the command java -ea Main?
Testing invariants by using assertions
Hard
A.An AssertionError is thrown.
B.x before assertion: 10\nx after assertion: 11
C.x before assertion: 10
D.x before assertion: 10\nx after assertion: 10
Correct Answer: x before assertion: 10\nx after assertion: 11
Explanation:
Let's refine the question to be trickier. What if the assertion passes but has a side effect?
java
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println("x before assertion: " + x);
assert modifyAndCheck(x);
System.out.println("x after assertion: " + x);
}
private static boolean modifyAndCheck(int val) {
// This method has a side effect, which is bad practice.
val = val + 5;
return val > 10;
}
}
In this case, val is a local copy, so x in main is not modified. Output would be 10 and 10.
Let's go back to the original idea but make the assertion pass.
java
// In Main.java
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println("x before assertion: " + x);
assert x++ >= 10 : "x should be >= 10";
System.out.println("x after assertion: " + x);
}
}
Here, x is 10. 10 >= 10 is true. The assertion passes. The side effect x++ still occurs. x becomes 11. The program continues and prints the new value of x. This is a great hard question because it relies on knowing both that the side effect happens and that the assertion condition passes. Let's use this version.
Final check: java -ea Main. x is 10. assert x++ >= 10. The expression x >= 10 is evaluated with x=10, which is true. The assertion passes. The post-increment x++ then updates x to 11. The next line prints x after assertion: 11. This is correct. If run without -ea, the assert line is skipped entirely, and the output would be ... 10 and ... 10.
Incorrect! Try again.
51What 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: 10
B.The program terminates with an AssertionError.
C.The program fails to compile.
D.x before assertion: 10\nx after assertion: 11
Correct Answer: x before assertion: 10\nx after assertion: 11
Explanation:
When assertions are enabled via the -ea flag, the expression inside the assert statement is evaluated. The expression here is x++ >= 10. Crucially, expressions in assertions are always evaluated if assertions are on, including any side effects.
The value of x (which is 10) is used for the comparison 10 >= 10. This evaluates to true, so the assertion passes and no AssertionError is thrown.
The post-increment operator ++ then updates the value of x to 11.
The program continues to the next line, which prints the new value of x. This demonstrates the danger of side effects in assertions, as program behavior can change depending on whether assertions are enabled.
Incorrect! Try again.
52Analyze the following exception propagation chain. What is the final output printed to the console?
Propagation of exceptions
Hard
A.Caught in B: Original\nCaught in A: Transformed
B.Caught in B: Original\nFinally in B\nProgram terminates due to an unhandled exception.
C.Caught in B: Original\nFinally in B\nCaught in A: Transformed
D.Caught in B: Original
Correct Answer: Caught in B: Original\nFinally in B\nCaught in A: Transformed
Explanation:
This demonstrates exception transformation and propagation.
methodC throws an IOException.
methodB's try block calls methodC, and the IOException is caught by catch (IOException e). It prints "Caught in B: Original".
Inside the catch block, a newRuntimeException is thrown.
Before methodB propagates this new exception, its finally block must execute, printing "Finally in B".
The RuntimeException (which is unchecked) propagates up to methodA.
methodA's catch block is catch (RuntimeException e), which successfully catches the transformed exception from methodB. It prints "Caught in A: Transformed". The original IOException is effectively consumed and replaced by the RuntimeException.
Incorrect! Try again.
53Why does the following Java code snippet fail to compile?
Handling multiple exceptions using multi-catch
Hard
A.The multi-catch statement cannot be used with custom exceptions.
B.The variable e in a multi-catch block is implicitly final and cannot be used to call methods like getMessage().
C.A multi-catch block requires a finally block to be present.
D.In a multi-catch block, one exception type cannot be a subclass of another exception type listed in the same block.
Correct Answer: In a multi-catch block, one exception type cannot be a subclass of another exception type listed in the same block.
Explanation:
The Java compiler enforces a rule for multi-catch blocks to prevent redundant code. If you list multiple exception types, none of them can be a superclass or subclass of another in the same catch clause. In this example, FileNotFoundException is a direct subclass of IOException. Therefore, catch (IOException e) would already handle any FileNotFoundException. The compiler flags catch (IOException | FileNotFoundException e) as an error because the FileNotFoundException part is unreachable and redundant. The variable e is indeed implicitly final in a multi-catch, but you can still call methods on it; you just can't reassign it.
Incorrect! Try again.
54You 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?
This question tests the handling of DST transitions in the java.time API. The initial time is 2024-03-10T01:30 with the standard offset for New York (-05:00). We add a Duration of 2 hours. A Duration represents an exact number of seconds (2 * 3600 seconds in this case) on the timeline. Adding 2 hours to 01:30 would arithmetically be 03:30. The ZonedDateTime API is DST-aware. At 02:00 on this date, the clock springs forward to 03:00, and the time zone offset changes from -05:00 (EST) to -04:00 (EDT). The API correctly calculates the resulting time as 03:30 and applies the new, correct offset for that time, which is -04:00.
Incorrect! Try again.
55What is the behavior of the following code when executed?
Exception class hierarchy and exception types
Hard
A.The program will print "Caught Error", "Finally", and then "Finished".
B.The program will enter an infinite loop and eventually crash without printing anything.
C.The program will print "Caught Error" and then "Finished".
D.The program will print "Finally" and then terminate by throwing a StackOverflowError.
Correct Answer: The program will print "Finally" and then terminate by throwing a StackOverflowError.
Explanation:
While it is syntactically possible to catch an Error, it is strongly discouraged because Error and its subclasses (like StackOverflowError) signify critical problems that a reasonable application should not try to handle. The recursive call to causeStackOverflow() will quickly exhaust the stack space and throw a StackOverflowError. Even though there is a catch(Error e) block, the JVM is in a precarious state. The finally block is almost always guaranteed to run, so it will print "Finally". However, after catching the error, the program cannot be expected to recover gracefully. The default main thread's uncaught exception handler will print the stack trace of the StackOverflowError, and the program will terminate abruptly. The line "Finished" will never be reached.
Incorrect! Try again.
56What is printed to the console when the main method of the Test class is executed?
Local and Anonymous class
Hard
A.Anonymous says: 10
B.Compilation Fails.
C.A NullPointerException is thrown.
D.Anonymous says: 11
Correct Answer: Anonymous says: 10
Explanation:
This tests the scope and capture mechanism of an anonymous class. The anonymous class implementing Speaker is defined inside the create method. It captures the value of the greeting parameter. The key is that it captures the value of the reference sb, not the StringBuilder object itself. Inside the main method, a StringBuilder with the value "10" is created. The create method is called, and the anonymous class instance is created, capturing the reference to this StringBuilder. After create returns, the line sb.append("1") modifies the sameStringBuilder object that the Speaker instance holds a reference to. However, the say() method of the anonymous class uses the captured local variablegreeting, not the instance field sb. The local variable greeting was never modified within the create method and its captured value remains a reference to the StringBuilder as it was when passed. Thus, when say() is called, it accesses the greeting field, which was assigned the value of the StringBuilder's toString() method at the time of the anonymous class's creation. The greeting field is a String, which is immutable. It was initialized to "10" and never changed. Therefore, it prints "Anonymous says: 10". If the anonymous class used sb.toString() directly in say(), the output would be "11".
Incorrect! Try again.
57Analyze the following nested class structure. What is the output of this program?
This code fails to compile due to an access rule violation. A static nested class (StaticInner in this case) does not have an enclosing instance of the outer class. Therefore, it cannot directly access non-static members of the outer class. The line System.out.println("Accessing: " + o_var); inside StaticInner.run() is trying to access o_var, which is a non-static instance variable of Outer. This is illegal and will result in a compilation error. A static nested class can only access static members of its enclosing class directly or non-static members through an explicit instance of the outer class (e.g., new Outer().o_var).
Incorrect! Try again.
58What is the output when the run method is executed, given the following Resource classes?
Autoclose resources with try-with-resources statement
Hard
The try-with-resources statement has a strict order of operations.
Initialization: Resources are initialized in the order they are declared. So, new R1() is executed first (printing "Creating R1"), followed by new R2() (printing "Creating R2").
Execution: The try block is executed (printing "Running...").
Closing: When the try block finishes, the resources are closed in the reverse order of their initialization. Therefore, r2.close() is called first (printing "Closing R2"), and then r1.close() is called (printing "Closing R1"). This LIFO (Last-In, First-Out) order for closing resources is crucial for managing dependencies correctly.
Incorrect! Try again.
59Consider 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 fails to compile because the variable factorial is not initialized when it is used inside the lambda.
B.The code compiles and prints 120.
C.The code compiles but throws a StackOverflowError at runtime.
D.The code fails to compile because a lambda expression cannot be recursive.
Correct Answer: The code fails to compile because the variable factorial is not initialized when it is used inside the lambda.
Explanation:
This is a classic problem with creating recursive lambdas. A local variable must be definitely assigned before it is used. In the statement Function<Integer, Integer> factorial = n -> ..., the right-hand side (the lambda expression) is evaluated to create an object to assign to the left-hand side (factorial). Inside the lambda body, the code refers to the variable factorial itself (factorial.apply(n - 1)). At this point, the compiler sees factorial being used before it has been assigned a value, leading to a compilation error. A common way to solve this is to use an instance variable or a static field, or a more complex construct like a y-combinator, so that the variable is in scope and initialized before the lambda body is defined.
Incorrect! Try again.
60An 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.This scenario causes a compilation error because an Inner instance cannot outlive its Outer instance.
B.The Outer instance will not be garbage collected because the Inner instance holds an implicit reference to it.
C.Both the Outer and Inner instances will be garbage collected together.
D.The Outer instance will be garbage collected, and the Inner instance will remain, but trying to access outer members will throw a NullPointerException.
Correct Answer: The Outer instance will not be garbage collected because the Inner instance holds an implicit reference to it.
Explanation:
A key characteristic of a non-static inner class (or member inner class) is that each of its instances holds a hidden, implicit reference to the instance of the outer class that created it. This reference is what allows the inner class to access members of the outer class. As long as the Inner instance is reachable (i.e., a strong reference to it exists), that implicit reference to the Outer instance will also be maintained. Because the Outer instance is still reachable through the Inner instance, it is not eligible for garbage collection. This behavior is a common source of memory leaks in Java if inner class instances are unintentionally kept alive.
Incorrect! Try again.
61What 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 then terminates with an uncaught SQLException.
C.The code fails to compile.
D.The program prints Level 2 and Level 1 and then terminates with an uncaught SQLException.
Correct Answer: The program prints Level 2 and Level 1 and then terminates with an uncaught SQLException.
Explanation:
This demonstrates exception handling with re-throwing.
level2() is called and immediately throws a new SQLException.
The catch block in level1() catches this exception.
Inside the catch block, it prints Level 2.
The line throw e; re-throws the exact sameSQLException object that was caught.
The finally block in level1() executes before the exception propagates further, printing Level 1.
The SQLException is now propagated out of level1() and into main().
Incorrect! Try again.
62Analyze the following custom exception class. What is a significant flaw in its design according to Java best practices?
Creating custom exceptions
Hard
A.It extends Exception, making it a checked exception, but its name (InvalidStateException) implies a programming error that should be unchecked.
B.A custom exception cannot have more than one constructor.
C.The exception class should be final to prevent further subclassing.
D.The constructor should not accept a Throwable cause.
Correct Answer: It extends Exception, making it a checked exception, but its name (InvalidStateException) implies a programming error that should be unchecked.
Explanation:
Java's exception philosophy distinguishes between recoverable conditions (checked exceptions, extending Exception) and programming errors/bugs (unchecked exceptions, extending RuntimeException). An InvalidStateException suggests that the program has reached a state it should not have, which is typically a bug or a logic error on the programmer's part. For such errors, an unchecked exception (extending RuntimeException) is the appropriate choice. Forcing callers to try-catch a bug they cannot realistically recover from is considered poor API design. The code is syntactically correct, but it violates a key design principle. The other options are incorrect: providing a cause is a standard and recommended practice, and there are no rules against subclassing exceptions or having multiple constructors.