☕ Java MCQ Questions – Page 123
Questions 2441–2460 of 3994 total — Java interview practice
▶ Practice All Java QuestionsWhat error occurs when compiling this Java code?
java
public class InvalidThrow {
public static void generateError() {
String message = "This is an error!";
throw message; // Trying to throw a String object
}
public static void main(String[] args) {
generateError();
}
}
When attempting to compile the provided Java code, which aims to create an immutable class, what will be the resulting error?
java
class ResourceData {
private String data;
public ResourceData(String data) { this.data = data; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
// Note: Does NOT implement Cloneable nor has a public clone() method
}
final class ServerConfig {
private final String host;
private final ResourceData resource;
public ServerConfig(String host, ResourceData resource) {
this.host = host;
this.resource = (ResourceData) resource.clone(); // Attempt to clone non-Cloneable object
}
public String getHost() { return host; }
public ResourceData getResource() { return (ResourceData) resource.clone(); }
}
public class DeepCopyError {
public static void main(String[] args) {
ResourceData initialData = new ResourceData("Default");
ServerConfig config = new ServerConfig("localhost", initialData);
}
}
What kind of error will occur when running this Java code?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("First line.");
bw.close(); // Stream is closed here
bw.write("Second line."); // Attempt to write to a closed stream
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
What does this code print?
java
import java.io.*;
class MyData implements Serializable {
private static final long serialVersionUID = 1L;
transient private int value;
private String name;
public MyData(int value, String name) {
this.value = value;
this.name = name;
}
public int getValue() { return value; }
public String getName() { return name; }
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeObject(name);
oos.writeInt(value * 2);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
this.name = (String) ois.readObject();
this.value = ois.readInt() / 2;
}
}
public class SerializationTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
MyData data = new MyData(10, "Original");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(data);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
MyData deserializedData = (MyData) ois.readObject();
ois.close();
System.out.println("Name: " + deserializedData.getName());
System.out.println("Value: " + deserializedData.getValue());
}
}
What error occurs when running this code, assuming 'nonexistent.txt' does not exist?
java
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class MyClass {
public static void main(String[] args) {
FileReader fr = null; // Initialized to null
try {
fr = new FileReader("nonexistent.txt");
fr.read();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
} finally {
try {
fr.close(); // Potential NullPointerException here
} catch (IOException e) {
System.err.println("Error closing: " + e.getMessage());
}
}
}
}
Where can the `synchronized` keyword be applied in Java?
Identify the compilation error in the given Java code snippet related to `Runnable` and an anonymous inner class.
java
public class Main {
public static void main(String[] args) {
String status = "Pending";
Runnable task = new Runnable() {
@Override
public void run() {
// This line causes an error
status = "Completed";
System.out.println("Task " + status);
}
};
new Thread(task).start();
}
}
What error will this Java code produce during compilation?
java
public class ArrayError {
public static void main(String[] args) {
int[][] grid = new int[2][2];
grid.length = 5;
}
}
What is the primary purpose of the 'load factor' in a `HashMap`?
What error occurs when running this Java code?
java
import java.io.IOException;
public class MainThrows {
public static void criticalTask() throws IOException {
System.out.println("Performing critical task...");
throw new IOException("Disk full error!");
}
public static void main(String[] args) throws IOException {
criticalTask(); // main method propagates the IOException
}
}
What type of error will occur when running this Java code?
java
public class Notifier {
private final Object lock = new Object();
public void sendNotification() {
// Missing synchronized(lock)
lock.notify();
System.out.println("Notified!");
}
public static void main(String[] args) {
Notifier notifier = new Notifier();
notifier.sendNotification();
}
}
Which statement accurately describes the requirement for objects to be stored in a `TreeSet` without providing a custom `Comparator`?
Which of the following describes the compilation error in the given Java code?
java
public class InvalidAssignment {
public static void main(String[] args) {
int a = 10;
int b = 20;
a + b = 30;
System.out.println(a);
}
}
What is the most likely error when executing this Java code snippet?
java
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.IOException;
class FaultyWriter extends Writer {
private String content = "";
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
content += new String(cbuf, off, len);
}
@Override
public void flush() throws IOException {
throw new IOException("Simulated flush error!");
}
@Override
public void close() throws IOException {
// Do nothing
}
@Override
public String toString() { return content; }
}
public class Test {
public static void main(String[] args) {
FaultyWriter fw = new FaultyWriter();
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Some data");
bw.flush(); // This is where the error will happen
} catch (IOException e) {
System.err.println("Caught Error: " + e.getMessage());
}
}
}
What is the output when this Java program runs?
java
public class OverloadDemo9 {
void operate(short s) {
System.out.println("Operating on short: " + s);
}
void operate(int i) {
System.out.println("Operating on int: " + i);
}
public static void main(String[] args) {
OverloadDemo9 obj = new OverloadDemo9();
byte b = 25;
obj.operate(b);
}
}
Which exception will be thrown when executing this Java code?
java
public class StringError9 {
public static void main(String[] args) {
String[] words = {"one", null, "three"};
String result = "";
for (String word : words) {
if (word.length() > 2) {
result += word;
}
}
System.out.println(result);
}
}
Given the following Java class:
java
class Overload {
void handle(String s) { System.out.println("String"); }
void handle(Integer i) { System.out.println("Integer"); }
}
What is the result of compiling and running the following code?
`new Overload().handle(null);`
What does this code print?
java
import java.io.*;
class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
private static Singleton INSTANCE = new Singleton();
private int value;
private Singleton() {
this.value = 100;
}
public static Singleton getInstance() {
return INSTANCE;
}
protected Object readResolve() {
return INSTANCE; // Always return the existing singleton instance
}
public void setValue(int value) { this.value = value; }
public int getValue() { return value; }
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Singleton s1 = Singleton.getInstance();
s1.setValue(200);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(s1);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Singleton s2 = (Singleton) ois.readObject();
ois.close();
System.out.println(s2.getValue());
System.out.println(s1 == s2);
}
}
What is the typical scope of a variable declared within the initialization part of a `for` loop (e.g., `for (int i = 0; ...)` )?
What is the error in the following Java code?
java
public class Main {
public static void main(String[] args) {
byte b = 10;
boolean flag = (boolean) b;
System.out.println(flag);
}
}