What error will occur when attempting to write to a non-existent directory '/nonexistent_dir/file.ser'?
java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.File;
public class Main {
public static void main(String[] args) {
String filePath = "/nonexistent_dir/file.ser"; // Path to a directory that likely doesn't exist
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
oos.writeObject("Hello");
} catch (IOException e) {
System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: A) FileNotFoundException
Attempting to create a file in a non-existent directory via `FileOutputStream` will result in a `FileNotFoundException` (a subclass of `IOException`), as the file path cannot be resolved.
Q262easycode error
What is the compilation error in the following Java code snippet?
java
public class LoopError {
public static void main(String[] args) {
int k = 0;
do {
System.out.println(k);
k++;
} while (k < 2);
break;
}
}
✅ Correct Answer: B) `break` statement outside of loop or switch.
The `break` statement on line 8 is outside the `do-while` loop's block. A `break` statement can only be used directly within a loop or a `switch` statement, otherwise, it results in a compile-time error.
Q263hardcode error
What is the error in this Java code snippet?
java
public class BuilderError {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
char ch = null;
sb.append(ch);
System.out.println(sb);
}
}
✅ Correct Answer: A) Compile-time error: incompatible types: <null> cannot be converted to char
A `char` primitive type cannot hold a `null` value. The assignment `char ch = null;` results in a compile-time type mismatch error, as `null` is not a valid character literal or value for a primitive `char`.
Q264medium
A method reference `ClassName::instanceMethod` (e.g., `String::toUpperCase`) refers to an instance method of an arbitrary object of a particular type. How does this differ from `object::instanceMethod` (e.g., `myString::toUpperCase`)?
✅ Correct Answer: B) `ClassName::instanceMethod` requires the functional interface's abstract method to accept an instance of `ClassName` as its first parameter, on which the method will be invoked. `object::instanceMethod` uses the pre-existing `object` as the receiver.
`ClassName::instanceMethod` is used when the receiver object is provided by the functional interface's parameters. `object::instanceMethod` uses a specific, already-defined `object` as the receiver for the instance method call.
Q265medium
Which two mechanisms are primarily used to achieve abstraction in Java?
✅ Correct Answer: B) Abstract Classes and Interfaces
Abstract classes and interfaces are the core language constructs in Java specifically designed to enforce abstraction by defining contracts and incomplete implementations.
Q266easy
If a thread calls `object.wait()` without a timeout, what state does it enter until `notify()` or `notifyAll()` is called?
✅ Correct Answer: D) WAITING
Calling `object.wait()` without a timeout causes the thread to release its lock and enter the WAITING state. It remains in this state indefinitely until notified.
Q267easy
Which of the following situations will most likely lead to an infinite `for` loop?
✅ Correct Answer: B) The loop condition always evaluates to `true` and never becomes `false`.
An infinite loop occurs when the loop's condition never becomes `false`, causing the loop to execute indefinitely.
Q268hard
Consider the Java snippet: `byte b = 10; char c = 'a'; int result = b + c;`. What is the value of `result`?
✅ Correct Answer: A) 107
When `byte` and `char` are operands in an arithmetic expression, both are promoted to `int` before the operation. The ASCII (or Unicode) value of 'a' is 97. Thus, `10 + 97` results in `107`.
Q269easy
What is the primary benefit of using inheritance in Java?
✅ Correct Answer: B) To promote code reusability
Inheritance allows a subclass to reuse fields and methods of an existing superclass, thereby promoting code reusability and reducing redundant code.
Q270hardcode error
What is the error in the execution of this Java code snippet?
java
public class BuilderError {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
char[] arr = null;
sb.insert(2, arr);
System.out.println(sb);
}
}
✅ Correct Answer: A) NullPointerException
The `StringBuilder.insert(int offset, char[] str)` method expects a non-null `char[]` argument. Passing `null` for the character array will result in a `NullPointerException` at runtime.
Q271hardcode error
What is the output of this code?
java
import java.io.File;
public class GetParentOfRoot {
public static void main(String[] args) {
File root = new File(File.separator); // Represents the root directory
File parent = root.getParentFile();
if (parent == null) {
System.out.println("Parent is null.");
} else {
System.out.println("Parent path: " + parent.getAbsolutePath());
}
}
}
✅ Correct Answer: B) Parent is null.
The `getParentFile()` method returns `null` when invoked on a `File` object that represents the root directory of the filesystem, as there is no parent above the root.
Q272easycode error
What error will occur when attempting to deserialize an object from 'empty.ser' which was created as an empty file?
java
import java.io.*;
public class Main {
public static void main(String[] args) {
String filename = "empty.ser";
try (FileOutputStream fos = new FileOutputStream(filename)) {
// File is created but nothing is written to it
} catch (IOException e) {
System.err.println("Error creating file: " + e.getMessage());
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
Object obj = ois.readObject(); // Attempt to read from an empty stream
System.out.println("Object deserialized.");
} catch (IOException | ClassNotFoundException e) {
System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: A) EOFException
When an `ObjectInputStream` attempts to read an object from a stream that has reached its end prematurely (e.g., an empty file where no object was written), an `EOFException` (End Of File Exception) is thrown.
Q273mediumcode error
What error occurs when running this Java code?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
String sub = sb.substring(0, 4);
System.out.println(sub);
}
}
✅ Correct Answer: C) StringIndexOutOfBoundsException
The `substring(int start, int end)` method, when called on a `StringBuffer`, behaves similarly to `String.substring()`. The `end` index (4) must be less than or equal to the length (3). Since 4 > 3, it throws a `StringIndexOutOfBoundsException`.
Q274hard
What is the outcome of attempting to cast a `null` reference to any non-primitive reference type, for example, `(String) null`?
✅ Correct Answer: C) The expression evaluates to `null` without throwing any exception.
Casting a `null` reference to any reference type always results in `null` itself. No `ClassCastException` or `NullPointerException` is thrown during the cast operation when the reference itself is `null`.
Q275easycode error
What will happen when this Java code is compiled?
java
public class MyClass {
public static void main(String[] args) {
int static = 10;
System.out.println(static);
}
}
✅ Correct Answer: C) A compilation error: 'static' is a keyword and cannot be used as a variable name.
Java keywords like 'static' are reserved and cannot be used as identifiers (variable names, method names, etc.). Attempting to do so will result in a compilation error.
Q276hardcode error
What is the error in this Java code snippet?
java
public class BuilderError {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Test");
char[] chars = {'a', 'b', 'c', 'd', 'e'};
sb.append(1, 2, chars);
System.out.println(sb);
}
}
✅ Correct Answer: A) Compile-time error: no suitable method found for append(int,int,char[])
There is no `StringBuilder.append` method overload that accepts arguments in the order `(int, int, char[])`. The correct overload for appending a sub-array is `append(char[] str, int offset, int len)`. This results in a compile-time error.
Q277medium
What is the key difference in focus between encapsulation and abstraction in object-oriented programming?
✅ Correct Answer: B) Encapsulation focuses on hiding implementation details and bundling data, while abstraction focuses on showing essential features and hiding complexity.
Encapsulation is about bundling data with methods and controlling access (data hiding), while abstraction is about showing only the necessary details and hiding complex implementation.
Q278easy
Is `java.lang.StringBuilder` thread-safe?
✅ Correct Answer: B) No, it is not synchronized and should not be used in multi-threaded environments without external synchronization.
`StringBuilder` is not thread-safe. For thread-safe string manipulation, `StringBuffer` should be used.
Q279mediumcode error
What kind of error will occur when compiling the following Java code, assuming 'some_file.txt' may or may not exist?
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TestClass {
public static void main(String[] args) {
FileReader fr = new FileReader("some_file.txt");
BufferedReader br = new BufferedReader(fr);
try {
br.readLine();
} catch (IOException e) {
System.err.println("IO Error");
} finally {
// Closing logic omitted
}
}
}
✅ Correct Answer: B) A compile-time error: unhandled exception type IOException.
The constructor `new FileReader("some_file.txt")` can throw a `FileNotFoundException` (a subclass of `IOException`), which is a checked exception. This exception is not handled by a `try-catch` block for the `FileReader` constructor itself, nor is it declared in the `main` method's `throws` clause, leading to a compile-time error.
Q280easycode error
What error occurs when `wait()` is called on an object without holding the object's lock?
java
public class Main {
public static void main(String[] args) {
Object lock = new Object();
try {
lock.wait(); // Calling wait() outside a synchronized block
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) java.lang.IllegalMonitorStateException
The `wait()` method can only be called by a thread that owns the monitor (lock) of the object. If called without holding the lock, an `IllegalMonitorStateException` is thrown at runtime.