☕ Java MCQ Questions – Page 12

Questions 221–240 of 3994 total — Java interview practice

▶ Practice All Java Questions
Q221 hard
Consider a `switch` statement nested within a `for` loop. If an unlabeled `break` statement is executed within a `case` block of this `switch` statement, what is the immediate effect on the execution flow?
Q222 hard
Consider a scenario where a constructor passes the `this` reference to another object before the current object's construction is complete. What is a primary encapsulation risk?
Q223 easy
What is the primary reason to use `StringBuilder` in Java?
Q224 easy code output
What is the output of this Java code snippet?
java
public class ArrayTest {
    public static void main(String[] args) {
        boolean[] flags = new boolean[2];
        flags[0] = true;
        System.out.println(flags[1]);
    }
}
Q225 easy
What kind of underlying data structure does `TreeMap` use to maintain its sorted order?
Q226 medium
For custom objects to be correctly stored and uniquely identified within a `HashSet`, which methods must be properly overridden in the custom class?
Q227 hard
Consider a Java construct using `do { ... } while (false);`. What is the primary and most common idiomatic use case for this specific `do-while` pattern?
Q228 medium
The `renameTo()` method of the `File` class can fail for several reasons. Which of the following is NOT a common reason for `renameTo()` to return `false`?
Q229 easy code error
What will be the outcome of attempting to compile this Java code?
java
class Constants {
    private static String API_KEY = "my_secret_key";
}

public class Config {
    public static void main(String[] args) {
        System.out.println(Constants.API_KEY);
    }
}
Q230 hard code error
What is the compile-time error when trying to instantiate the Inner class from a static context?
java
class Outer {
    class Inner {
        Inner() {}
    }

    static class Nested {
        void createInnerInstance() {
            // Attempt to instantiate non-static inner class
            Inner inner = new Inner();
        }
    }
}
Q231 hard
Under what specific conditions does a HashMap bucket (linked list) transition into a Red-Black Tree in Java 8 and later?
Q232 hard code output
What is the output of this code?
java
public class Q5_LostNotify {
    private static final Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("T: Attempting to wait.");
                    lock.wait();
                    System.out.println("T: Notified.");
                } catch (InterruptedException e) {
                    System.out.println("T: Interrupted.");
                }
            }
            System.out.println("T: Finished its synchronized block.");
        });
        
        synchronized (lock) {
            System.out.println("Main: Notifying lock (no one waiting yet).");
            lock.notify(); // This notify is lost
            System.out.println("Main: Notify finished.");
        }

        t.start();
        Thread.sleep(200); // Give t time to enter WAITING
        System.out.println("Main: T state after some time: " + t.getState());
        // The program will hang unless interrupted or notified again.
        t.interrupt(); // To ensure termination for output
        Thread.sleep(50);
        System.out.println("Main: T state after interrupt: " + t.getState());
    }
}
Q233 medium code output
What is the output of this Java code snippet?
java
public class StringBufferTest {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Programming");
        sb.delete(3, 7);
        sb.deleteCharAt(2);
        System.out.print(sb);
    }
}
Q234 hard code error
What exception is thrown when the `ois.readObject()` line is executed during deserialization?
java
import java.io.*;

class NullPointerInReadObject implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private transient String transientField; // Marked transient, so not serialized by default

    public NullPointerInReadObject(String name) {
        this.name = name;
        this.transientField = "Initialized";
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject(); // Reads 'name'. 'transientField' is not automatically read.
        // Attempting to use transientField, which is null after defaultReadObject,
        // as it was not part of the default serialization and no custom logic initialized it.
        System.out.println("Transient field length: " + transientField.length()); // Error occurs here
    }

    public String getName() { return name; }
    public String getTransientField() { return transientField; }
}

public class SerializationError10 {
    public static void main(String[] args) throws Exception {
        NullPointerInReadObject obj = new NullPointerInReadObject("Test Object");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        byte[] serializedData = bos.toByteArray();
        oos.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
        ObjectInputStream ois = new ObjectInputStream(bis);
        NullPointerInReadObject deserialized = (NullPointerInReadObject) ois.readObject(); // Error occurs during readObject
        ois.close();
        System.out.println("Deserialized: " + deserialized.getName());
    }
}
Q235 easy code error
What happens when you try to compile and run this Java code?
java
public class FinalArrayReassignment {
    public static void main(String[] args) {
        final int[] numbers = {1, 2, 3};
        numbers[0] = 10;
        numbers = new int[]{4, 5, 6};
        System.out.println(numbers[0]);
    }
}
Q236 hard code error
Does this Java code compile? If not, what is the compile-time error?
java
import java.io.IOException;
class Parent {
    public void perform() throws IOException {}
}
class Child extends Parent {
    @Override
    public void perform() throws Exception {}
}
public class Main {
    public static void main(String[] args) {}
}
Q237 medium code output
What is the output of this Java code snippet?
java
import java.util.ArrayList;
import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        Iterator<Integer> it = numbers.iterator();
        while (it.hasNext()) {
            if (it.next() == 20) {
                it.remove();
            }
        }
        System.out.println(numbers);
    }
}
Q238 easy code error
What is the error in this Java code?
java
public class FileWriterError3 {
    public static void main(String[] args) {
        // Missing import statement for FileWriter
        java.io.FileWriter writer = null;
        try {
            writer = new java.io.FileWriter("log.txt");
            writer.write("Log message.");
        } catch (java.io.IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Q239 medium
Which statement accurately describes a Java functional interface?
Q240 hard code error
What compile-time error occurs when attempting to compile this Java code?
java
abstract class Vehicle {
    public abstract void start();
}

class Car extends Vehicle {
    @Override
    protected void start() {
        System.out.println("Car starting...");
    }
}
← Prev 1011121314 Next → Page 12 of 200 · 3994 questions