☕ Java MCQ Questions – Page 96

Questions 1901–1920 of 3994 total — Java interview practice

▶ Practice All Java Questions
Q1901 hard code error
What compile-time error will this Java code produce?
java
interface MyInterface {
    int VALUE = 10;
    MyInterface() {
        System.out.println("Initializing interface");
    }
}
Q1902 medium code output
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));
    }
}
Q1903 easy code error
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);
    }
}
Q1904 easy code output
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());
        }
    }
}
Q1905 medium code output
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());
        }
    }
}
Q1906 hard code error
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
    }
}
Q1907 easy
Is `TreeMap` thread-safe?
Q1908 easy
Which method is used to get the number of characters in a String object in Java?
Q1909 easy code error
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);
    }
}
Q1910 medium
Consider a class `MyClass` that implements `Serializable`. If a field within `MyClass` is declared `transient`, what will be its value upon deserialization?
Q1911 medium code output
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));
    }
}
Q1912 medium code error
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());
        }
    }
}
Q1913 easy code output
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);
    }
}
Q1914 medium code output
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());
    }
}
Q1915 hard code error
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();
    }
}
Q1916 hard code output
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);
    }
}
Q1917 easy code error
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));
    }
}
Q1918 hard code output
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();
    }
}
Q1919 medium code output
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);
    }
}
Q1920 medium
What is the primary role of the `peek()` intermediate operation in a Stream pipeline?
← Prev 9495969798 Next → Page 96 of 200 · 3994 questions