☕ Java MCQ Questions – Page 27

Questions 521–540 of 3994 total — Java interview practice

▶ Practice All Java Questions
Q521 hard code error
What error will this Java code produce when compiled and run?
java
public class MixedArrayInit {
    public static void main(String[] args) {
        int[] data = new int[]{10, 20};
        // Attempt to create an array using both dimension expression and initializer list
        data = new int[2]{30, 40};
        System.out.println(data[0]);
    }
}
Q522 easy code output
What is the output of the following Java code?
java
public class OverloadDemo3 {
    void calculate(int a, int b) {
        System.out.println("Sum of ints: " + (a + b));
    }
    void calculate(double a, double b) {
        System.out.println("Sum of doubles: " + (a + b));
    }
    public static void main(String[] args) {
        OverloadDemo3 obj = new OverloadDemo3();
        obj.calculate(5, 5);
    }
}
Q523 easy
Which method is used to check if a String object contains no characters (i.e., its length is 0)?
Q524 hard
What happens if an `Integer` variable holds a `null` value and is then unboxed to a primitive `int`?
Q525 hard code error
What is the compilation error in the following Java code?
java
public enum Permission {
    READ("read"),
    WRITE("write"),
    EXECUTE("execute");

    private final String code;
    private String description; // Private mutable field

    private Permission(String code) {
        this.code = code;
        this.description = "Permission to " + code;
    }

    public String getCode() { return code; }
}

public class PermissionChecker {
    public static void main(String[] args) {
        // Attempt to access a private field of an enum constant
        System.out.println(Permission.READ.description); 
    }
}
Q526 hard code error
What compilation error will occur in this Java code?
java
class Test {
    public static void main(String[] args) {
        do {
            System.out.println("Attempting operation...");
            throw new java.io.IOException("File error");
        } while (false);
        System.out.println("Operation finished.");
    }
}
Q527 medium
After the statement `String[] names = new String[5];` is executed, what is the initial value of `names[0]`?
Q528 hard
What is a significant pitfall when using `double` or `float` variables as loop counters or in loop conditions, specifically when aiming for an exact number of iterations or comparison for equality?
Q529 hard code output
What does this code print?
java
public class Test {
    public static void main(String[] args) {
        try {
            System.out.print("Outer Try ");
            try {
                System.out.print("Inner Try ");
                throw new Exception("Inner Exception");
            } finally {
                System.out.print("Inner Finally ");
            }
        } catch (Exception e) {
            System.out.print("Outer Catch: " + e.getMessage());
        } finally {
            System.out.print("Outer Finally ");
        }
        System.out.print("End");
    }
}
Q530 hard code error
What error will this code throw when `t1` attempts to call `resource.release()`?
java
import java.util.concurrent.locks.ReentrantLock;

public class LockUnlockError {
    private static ReentrantLock resourceLock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            // t1 does not acquire the lock
            System.out.println("T1 trying to unlock without owning...");
            resourceLock.unlock(); 
            System.out.println("T1 unlocked (should not happen)");
        });

        t1.start();
    }
}
Q531 medium code error
What exception will be thrown when executing this Java code snippet?
java
import java.util.PriorityQueue;

public class QueueError {
    public static void main(String[] args) {
        PriorityQueue<String> pq = new PriorityQueue<>();
        pq.add("Hello");
        pq.add(null); // Adding a null element
    }
}
Q532 hard code error
What is the compile-time error in the following Java switch expression?
java
public class PrimitiveSwitchNullCaseError {
    public static void main(String[] args) {
        int number = 10;
        String category = switch (number) { // Error expected here
            case 5 -> "Small";
            case 10 -> "Medium";
            case null -> "Null Input"; // Invalid case
            default -> "Large";
        };
        System.out.println(category);
    }
}
Q533 hard code output
What is the output of this Java program, demonstrating `volatile` keyword behavior?
java
public class VolatileRunnable {
    private static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Runnable stopTask = () -> {
            System.out.println(Thread.currentThread().getName() + " started.");
            while (running) {
                // busy-wait
            }
            System.out.println(Thread.currentThread().getName() + " stopped.");
        };

        Thread worker = new Thread(stopTask, "WorkerThread");
        worker.start();

        Thread.sleep(100); // Give worker a chance to start
        running = false; // Change volatile flag

        Thread.sleep(100); // Give worker a chance to see the change
        System.out.println("Main thread finished setting running to false.");
    }
}
Q534 medium code output
What does this code print to the console?
java
import java.util.stream.IntStream;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream.range(1, 4)
                                         .map(n -> n * 10)
                                         .boxed()
                                         .collect(Collectors.toList());
        System.out.println(numbers);
    }
}
Q535 easy
Which operator is commonly used for concatenating (joining) two String objects in Java?
Q536 easy
What is the primary characteristic of a `TreeMap` regarding the order of its elements?
Q537 easy
Which of the following access modifiers can be used with a constructor in Java?
Q538 medium code error
What is the output of this Java code?
java
import java.io.*;

public class DeserializationError4 {
    public static void main(String[] args) {
        // This byte array represents a serialized object of a class named 'MyRemoteClass'
        // that has serialVersionUID = 1L. The actual definition of 'MyRemoteClass' is not provided.
        // We assume it was serialized previously.
        byte[] serializedData = { (byte)0xac, (byte)0xed, (byte)0x00, (byte)0x05, (byte)0x73, (byte)0x72, (byte)0x00, (byte)0x0e, (byte)0x4d, (byte)0x79, (byte)0x52, (byte)0x65, (byte)0x6d, (byte)0x6f, (byte)0x74, (byte)0x65, (byte)0x43, (byte)0x6c, (byte)0x61, (byte)0x73, (byte)0x73, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x00, (byte)0x01, (byte)0x4c, (byte)0x00, (byte)0x04, (byte)0x6e, (byte)0x61, (byte)0x6d, (byte)0x65, (byte)0x74, (byte)0x00, (byte)0x12, (byte)0x4c, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67, (byte)0x2f, (byte)0x53, (byte)0x74, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x67, (byte)0x3b, (byte)0x78, (byte)0x70, (byte)0x74, (byte)0x00, (byte)0x06, (byte)0x48, (byte)0x65, (byte)0x6c, (byte)0x6c, (byte)0x6f, (byte)0x21 };

        // Current class definition for deserialization
        class MyRemoteClass implements Serializable {
            private static final long serialVersionUID = 2L; // Changed SUID
            String name;
            public MyRemoteClass() { this.name = "Default"; }
            public MyRemoteClass(String name) { this.name = name; }
            @Override public String toString() { return "MyRemoteClass: " + name; }
        }

        try (ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            MyRemoteClass obj = (MyRemoteClass) ois.readObject();
            System.out.println(obj);
        } catch (Exception e) {
            System.out.println("Error: " + e.getClass().getName() + ": " + e.getMessage().split(";")[0]);
        }
    }
}
Q539 hard code output
What is the output of this Java code?
java
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileWriterOverwriteEmpty {
    public static void main(String[] args) {
        String filename = "overwrite_empty.txt";
        try {
            try (FileWriter fw = new FileWriter(filename)) { fw.write("Original content."); }

            try (FileWriter fw = new FileWriter(filename)) {
                // Nothing written here, but FileWriter opens in non-append mode
            }

            try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
                String line = br.readLine();
                System.out.println("Content: '" + (line != null ? line : "[Empty]") + "'");
            }
        } catch (IOException e) { System.out.println("Error: " + e.getMessage());
        } finally { try { Files.deleteIfExists(Path.of(filename)); } catch (IOException ignored) {} }
    }
}
Q540 easy code error
What is the result of running this Java code?
java
public class StringError {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length());
    }
}
← Prev 2526272829 Next → Page 27 of 200 · 3994 questions