☕ Java MCQ Questions – Page 22

Questions 421–440 of 3994 total — Java interview practice

▶ Practice All Java Questions
Q421 medium code output
What is the result of executing this code?
java
class ConditionalThrows {
    static void performAction(boolean shouldThrow) throws java.io.IOException {
        if (shouldThrow) {
            throw new java.io.IOException("Simulated IO failure");
        }
        System.out.println("Action completed successfully.");
    }

    public static void main(String[] args) {
        try {
            performAction(false);
            performAction(true);
            System.out.println("This line is unreachable.");
        } catch (java.io.IOException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Q422 medium
Why can a `private` method in a superclass not be overridden in a subclass?
Q423 medium code output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.NotNull;
import java.util.Set;

public class Test {
    static class Address {
        @NotNull public String street;
        public Address(String street) { this.street = street; }
    }
    static class User {
        // No @Valid here!
        public Address address; 
        public User(Address address) { this.address = address; }
    }
    public static void main(String[] args) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        User user = new User(new Address(null)); // Invalid street
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        System.out.println("Violations: " + violations.size());
    }
}
Q424 hard code error
What error occurs when running this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class IteratorDoubleRemove {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("hello", "world", "java"));
        Iterator<String> it = words.iterator();
        
        it.next(); // "hello"
        it.remove(); // Removes "hello"
        
        it.remove(); // Attempt to remove again without next() or previous()
    }
}
Q425 hard
Which statement accurately describes a key advantage of `ConcurrentLinkedQueue` over `LinkedBlockingQueue` in a highly concurrent, unbound scenario where elements are frequently added and removed?
Q426 hard
When calling `super.someMethod()` from within an overridden method in a subclass, how does this interaction subtly relate to polymorphism?
Q427 easy code error
Which compilation error will occur in the given Java code?
java
import java.util.function.Consumer;

@FunctionalInterface
interface MyLogger {
    default void log(String message) {
        System.out.println("[LOG]: " + message);
    }
    static void info(String message) {
        System.out.println("[INFO]: " + message);
    }
}

public class Main {
    public static void main(String[] args) {
        // Attempt to use MyLogger
    }
}
Q428 hard
How does the `BufferedWriter.newLine()` method determine the platform-specific line separator character sequence to write?
Q429 hard
A `while` loop's condition depends on a non-`volatile` boolean flag `running` which is set to `false` by another thread. Why might the loop `while(running)` unexpectedly continue spinning indefinitely, even after the other thread sets `running` to `false`, in a heavily optimized JVM environment?
Q430 hard code output
What is the output of this Java code?
java
import java.util.Comparator;
import java.util.TreeMap;

class ReverseIntegerComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer i1, Integer i2) {
        return i2.compareTo(i1); // Descending order
    }
}

public class Test {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>(new ReverseIntegerComparator());
        map.put(1, "A");
        map.put(5, "E");
        map.put(3, "C");
        map.put(2, "B");
        map.put(4, "D");
        System.out.println(map.firstKey() + ", " + map.lastKey());
    }
}
Q431 medium code output
What is the output of this Java code?
java
class MyRunnable implements Runnable {
    private String name;
    public MyRunnable(String name) { this.name = name; }
    public void run() {
        System.out.println(name + " started.");
        try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        System.out.println(name + " finished.");
    }
}
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MyRunnable("Worker"));
        t.start();
        t.join();
        System.out.println("Main thread done.");
    }
}
Q432 hard code error
What exception is thrown when the `ois.readObject()` line is executed during deserialization?
java
import java.io.*;

class Singleton implements Serializable {
    private static final long serialVersionUID = 1L;
    private static Singleton INSTANCE = new Singleton();
    private String data = "Initial Data";

    private Singleton() {
        // Constructor logic
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    // Incorrect readResolve implementation
    protected Object readResolve() {
        return new Object(); // Should return INSTANCE to maintain singleton property
    }

    public String getData() { return data; }
    public void setData(String data) { this.data = data; }
}

public class SerializationError6 {
    public static void main(String[] args) throws Exception {
        Singleton s1 = Singleton.getInstance();
        s1.setData("Modified Data");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(s1);
        byte[] serializedData = bos.toByteArray();
        oos.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Singleton s2 = (Singleton) ois.readObject(); // Error occurs here
        ois.close();

        System.out.println("Are they same instance? " + (s1 == s2));
        System.out.println("s1 data: " + s1.getData());
        System.out.println("s2 data: " + s2.getData());
    }
}
Q433 easy
What is the primary function of the `break` keyword in Java?
Q434 medium
What is the key distinction between the `mkdir()` and `mkdirs()` methods of the `File` class?
Q435 easy
When `Thread.sleep(long millis)` is called, what state does the current thread transition to?
Q436 easy
What happens if you try to access an element at an invalid index (e.g., negative or beyond the array's length) in a Java array?
Q437 easy
Consider a `java.util.Date` object. Is it mutable or immutable?
Q438 easy code error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Map<String, String> myMap = new HashMap<>();
        myMap.put("fruit", "apple");
        String item = myMap["fruit"];
        System.out.println(item);
    }
}
Q439 easy
What does the `this` keyword refer to inside a lambda expression?
Q440 hard
When `Object.notifyAll()` is called on an object where multiple threads are currently in the `WAITING` state, what is the state transition for *all* these waiting threads *before* they can potentially resume execution in the `RUNNABLE` state?
← Prev 2021222324 Next → Page 22 of 200 · 3994 questions