☕ Java MCQ Questions – Page 150
Questions 2981–3000 of 3994 total — Java interview practice
▶ Practice All Java QuestionsWhat is the error in this code?
java
import java.util.TreeMap;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "A");
map.put(2, "B");
for (Integer key : map.keySet()) {
if (key == 1) {
map.remove(key);
}
}
System.out.println(map.size());
}
}
What will be the result of compiling and running this Java code?
java
import java.lang.reflect.Constructor;
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
if (instance != null) {
// throw new RuntimeException("Use getInstance()"); // Omitted for clarity in options
}
}
public static Singleton getInstance() {
return instance;
}
public static void main(String[] args) throws Exception {
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
// constructor.setAccessible(true); // Missing critical line
Singleton newInstance = constructor.newInstance();
System.out.println(newInstance == instance);
}
}
What error will occur when running the following Java code?
java
public class StopThreadError {
public static void main(String[] args) {
Thread t = new Thread(() -> {
try {
Thread.sleep(5000); // Simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t.start();
t.stop(); // Deprecated method
}
}
Which statement accurately describes the initialization of `final` instance variables in Java constructors?
What compile-time error will this code produce?
java
class WorkerTask implements Runnable {
public void doWork() {
System.out.println("Doing work...");
}
}
public class Main {
public static void main(String[] args) {
WorkerTask task = new WorkerTask();
new Thread(task).start();
}
}
What is the compile-time error in this Java code?
java
import java.io.IOException;
import java.util.function.Consumer;
public class LambdaError {
public static void process(Consumer<String> consumer) {
// Does not declare IOException
}
public static void main(String[] args) {
process(s -> {
if (s.equals("error")) {
throw new IOException("Simulated IO Error"); // Checked exception
}
System.out.println(s);
});
}
}
For simple, single-variable updates (e.g., incrementing a counter), why might using `java.util.concurrent.atomic.AtomicInteger` be preferred over a `synchronized` block around an `int` variable?
What is the output of this Java code snippet?
java
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
File file = new File("temp_file_q7.txt");
try {
file.createNewFile();
System.out.println(file.length());
} catch (IOException e) {
System.out.println("Error");
} finally {
file.delete(); // Clean up
}
}
}
Which of the following statements about method overriding in Java is true?
What is the output of this Java code, specifically regarding the exception handling?
java
public class RunnableException {
public static void main(String[] args) throws InterruptedException {
Runnable buggyTask = () -> {
System.out.println("Buggy task running...");
throw new RuntimeException("Oops, an error occurred!");
};
Thread t = new Thread(buggyTask);
t.setUncaughtExceptionHandler((thread, e) -> {
System.out.println("Caught exception from thread " + thread.getName() + ": " + e.getMessage());
});
t.start();
t.join();
System.out.println("Main thread continues.");
}
}
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("apple");
words.add(123); // Attempt to add an Integer to a List<String>
System.out.println(words);
}
}
Consider the expressions `String.valueOf((Object) null)` and `(String) null`. What is the fundamental difference in their outcome or behavior?
What does this Java code print, demonstrating a potential encapsulation issue with Java Records?
java
import java.util.ArrayList;
import java.util.List;
record UserPermissions(String username, List<String> permissions) {}
public class Main {
public static void main(String[] args) {
List<String> userRoles = new ArrayList<>(List.of("READ", "WRITE"));
UserPermissions user = new UserPermissions("admin", userRoles);
System.out.println("Initial permissions: " + user.permissions());
user.permissions().add("DELETE");
System.out.println("Permissions after modification: " + user.permissions());
}
}
What is the runtime error encountered when executing this Java code snippet?
java
import java.util.HashSet;
import java.util.Objects;
class NodeA {
NodeB nodeB;
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeA nodeA = (NodeA) o;
return Objects.equals(this.nodeB, nodeA.nodeB);
}
public int hashCode() { return 1; }
public void setNodeB(NodeB nodeB) { this.nodeB = nodeB; }
}
class NodeB {
NodeA nodeA;
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeB nodeB = (NodeB) o;
return Objects.equals(this.nodeA, nodeB.nodeA);
}
public int hashCode() { return 1; }
public void setNodeA(NodeA nodeA) { this.nodeA = nodeA; }
}
public class Main {
public static void main(String[] args) {
HashSet<NodeA> set = new HashSet<>();
NodeA a = new NodeA();
NodeB b = new NodeB();
a.setNodeB(b);
b.setNodeA(a);
set.add(a);
}
}
What is the runtime error in the following Java code snippet?
java
import java.util.ArrayList;
public class Question4 {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
System.out.println(nums.get(0));
}
}
What does this code print?
java
import java.io.*;
class CustomSerializedUser implements Serializable {
private String username;
private transient String secretPin; // marked transient
public CustomSerializedUser(String username, String secretPin) {
this.username = username;
this.secretPin = secretPin;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeUTF(secretPin); // Manually serialize transient field
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.secretPin = in.readUTF(); // Manually deserialize transient field
}
public String getDetails() {
return "User: " + username + ", Pin: " + secretPin;
}
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
CustomSerializedUser user = new CustomSerializedUser("bob", "1234");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(user);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
CustomSerializedUser deserializedUser = (CustomSerializedUser) ois.readObject();
ois.close();
System.out.println(deserializedUser.getDetails());
}
}
In which Java package is the `Runnable` interface located?
What does this code print?
java
public class OperatorChallenge {
public static void main(String[] args) {
int a = 5;
int b = 2;
System.out.println(a + b * 2 >> 1 & 4);
}
}
What error will occur when this code is executed?
java
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.insert(5, "EE");
System.out.println(sb);
}
}
The `throws` keyword is primarily used to declare which type of exceptions in a method signature?