☕ Java MCQ Questions – Page 96
Questions 1901–1920 of 3994 total — Java interview practice
▶ Practice All Java QuestionsWhat compile-time error will this Java code produce?
java
interface MyInterface {
int VALUE = 10;
MyInterface() {
System.out.println("Initializing interface");
}
}
What does this Java code print to the console?
java
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
default int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
}
public class Test {
public static void main(String[] args) {
Calculator multiply = (a, b) -> a * b;
System.out.println(multiply.operate(5, 3));
System.out.println(multiply.add(5, 3));
System.out.println(Calculator.subtract(5, 3));
}
}
What is the error in this Java code?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterError10 {
public static void main(String[] args) {
String data = "Important data.";
try (FileWriter writer = new FileWriter("log_file.txt")) {
// This block is for writing.
}
// Trying to write outside the try-with-resources block
writer.write(data);
}
}
What is the output of this code?
java
class MyCustomCheckedException extends Exception {
public MyCustomCheckedException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new MyCustomCheckedException("Something went wrong!");
} catch (MyCustomCheckedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
What is the output of this code?
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> items = new ArrayList<>(List.of("One", "Two", "Three"));
Iterator<String> it = items.iterator();
try {
while (it.hasNext()) {
String item = it.next();
if ("Two".equals(item)) {
items.add("Four"); // Modifying collection directly during iteration
}
}
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
What is the runtime error encountered when executing this Java code snippet?
java
import java.util.HashSet;
import java.util.Objects;
class KeyWithNullableString {
String name;
public KeyWithNullableString(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyWithNullableString that = (KeyWithNullableString) o;
return name.equals(that.name); // Potential NPE
}
@Override
public int hashCode() { return Objects.hashCode(name); }
}
public class Main {
public static void main(String[] args) {
HashSet<KeyWithNullableString> set = new HashSet<>();
set.add(new KeyWithNullableString(null)); // Object with null 'name' field added
set.contains(new KeyWithNullableString(null)); // Triggers equals() call
}
}
Is `TreeMap` thread-safe?
Which method is used to get the number of characters in a String object in Java?
What is the error in the following Java code?
java
public class Main {
public static void main(String[] args) {
boolean flag = true;
int value = (int) flag;
System.out.println(value);
}
}
Consider a class `MyClass` that implements `Serializable`. If a field within `MyClass` is declared `transient`, what will be its value upon deserialization?
What is the output of this Java code snippet?
java
import java.util.TreeMap;
public class TreeMapNavigational {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(30, "Thirty");
System.out.println(map.floorKey(25) + "," + map.ceilingKey(25));
}
}
What error occurs when compiling this Java code?
java
import java.io.IOException;
public class UnreachableCatch {
public static void doSomething() {
System.out.println("Doing something...");
}
public static void main(String[] args) {
try {
doSomething();
} catch (IOException e) { // Catching a checked exception that cannot be thrown here
System.err.println("Caught an IOException: " + e.getMessage());
}
}
}
What does this code print?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Mathematics");
sb.setLength(5);
System.out.print(sb);
}
}
What does this code print?
java
import java.io.*;
class ExternalizableUser implements Externalizable {
private String name;
private transient int age;
public String department;
public ExternalizableUser() { /* no-arg constructor */ }
public ExternalizableUser(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name); // Only name is explicitly written
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF(); // Only name is explicitly read
}
public String getInfo() {
return "Name: " + name + ", Age: " + age + ", Dept: " + department;
}
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ExternalizableUser user = new ExternalizableUser("Alice", 30, "HR");
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);
ExternalizableUser deserializedUser = (ExternalizableUser) ois.readObject();
ois.close();
System.out.println(deserializedUser.getInfo());
}
}
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class WrongNotify {
private Object lockA = new Object();
private Object lockB = new Object();
public static void main(String[] args) throws InterruptedException {
WrongNotify demo = new WrongNotify();
Thread waitingThread = new Thread(() -> {
synchronized (demo.lockA) { // Acquires lockA
try { demo.lockA.wait(); } catch (InterruptedException e) {}
}
});
Thread notifyingThread = new Thread(() -> {
try {
Thread.sleep(100);
synchronized (demo.lockB) { // Acquires lockB
demo.lockA.notify(); // Problem line
}
} catch (InterruptedException | IllegalMonitorStateException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
});
waitingThread.start();
notifyingThread.start();
waitingThread.join();
notifyingThread.join();
}
}
What is the output of this code?
java
import java.io.*;
class TestObject implements Serializable {
private static final long serialVersionUID = 1L;
final int value1 = 10;
transient final String value2 = "Secret";
}
public class SerializationTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
TestObject obj = new TestObject();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
TestObject deserializedObj = (TestObject) ois.readObject();
ois.close();
System.out.println("Value1: " + deserializedObj.value1);
System.out.println("Value2: " + deserializedObj.value2);
}
}
What is the result of running this Java code?
java
public class StringError {
public static void main(String[] args) {
String sentence = "Java is fun";
int index = sentence.indexOf('x');
System.out.println(sentence.charAt(index));
}
}
What is the output of this code?
java
import java.util.function.Supplier;
public class LambdaShadowing {
private int value = 10;
public void execute() {
int value = 20;
Supplier<Integer> supplier = () -> {
// int value = 30; // This line would cause a compile error
return this.value + value;
};
System.out.println(supplier.get());
}
public static void main(String[] args) {
new LambdaShadowing().execute();
}
}
What does this Java code print to the console?
java
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<>(Arrays.asList("X", "Y", "Z"));
ArrayList<String> list2 = new ArrayList<>(Arrays.asList("Y", "W"));
list1.addAll(list2);
list1.removeAll(Arrays.asList("Y"));
System.out.println(list1);
}
}
What is the primary role of the `peek()` intermediate operation in a Stream pipeline?