☕ Java MCQ Questions – Page 32

Questions 621–640 of 3994 total — Java interview practice

▶ Practice All Java Questions
Q621 medium code error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;

public class MyClass {
    public static void main(String[] args) {
        List<String> emptyList = new ArrayList<>();
        emptyList.remove(0); // Attempt to remove from an empty list
        System.out.println(emptyList.size());
    }
}
Q622 hard code error
What runtime error will this Java code snippet throw?
java
public class Test {
    public static void main(String[] args) {
        int[][] original = new int[2][];
        original[0] = new int[]{1, 2};
        int[][] cloned = new int[2][];
        cloned[0] = original[0].clone();
        cloned[1] = original[1].clone();
        System.out.println(cloned[0][0]);
    }
}
Q623 easy code error
What is the error in the following Java code snippet?
java
public class ArrayError {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        numbers = {4, 5, 6};
    }
}
Q624 hard code error
Which exception is thrown when the `main` method of this Java code is executed on a modern JVM (JDK 9 or later)?
java
import java.lang.reflect.Field;

public class StringReflectionHack {
    public static void main(String[] args) throws Exception {
        String s1 = "Hello";
        Field valueField = String.class.getDeclaredField("value");
        valueField.setAccessible(true);
        char[] chars = (char[]) valueField.get(s1);
        chars[0] = 'J';
        System.out.println(s1);
    }
}
Q625 easy code error
Which error will occur when running this Java code?
java
import java.io.FileReader;
import java.io.IOException;

public class FileReaderIssue {
    public static void main(String[] args) throws IOException {
        String fileName = null;
        FileReader reader = new FileReader(fileName);
        int data = reader.read();
        reader.close();
    }
}
Q626 medium
What happens if an `if` statement in Java is immediately followed by two statements without being enclosed in curly braces `{}`?
Q627 medium code error
What is the compilation error in the provided Java code?
java
import java.io.IOException;

class Worker {
    public void performTask() throws IOException {
        System.out.println("Task performed by Worker");
    }
}

class Specialist extends Worker {
    @Override
    public void performTask() throws Exception { // ERROR: broader checked exception
        System.out.println("Task performed by Specialist");
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        Worker w = new Specialist();
        w.performTask();
    }
}
Q628 easy code output
What is the output of this Java code?
java
public class Worker implements Runnable {
    private String name;

    public Worker(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(name + " is working.");
    }

    public static void main(String[] args) {
        new Thread(new Worker("Alice")).start();
    }
}
Q629 medium code output
What is the output of this code?
java
import java.io.File;
import java.io.IOException;

public class FilePermissions {
    public static void main(String[] args) throws IOException {
        File file = new File("perms_test.txt");
        file.createNewFile();
        boolean readable = file.canRead();
        boolean writable = file.canWrite();
        boolean executable = file.canExecute();
        file.delete(); // Cleanup
        System.out.println(readable + ", " + writable + ", " + executable);
    }
}
Q630 easy code output
What is the output of this code?
java
class UnsafeCounter {
    private int count = 0;
    public void increment() {
        int temp = count; 
        temp++;
        count = temp;
        System.out.print(count);
    }
}

public class MyProgram {
    public static void main(String[] args) throws InterruptedException {
        UnsafeCounter uc = new UnsafeCounter();
        Thread t1 = new Thread(() -> uc.increment());
        Thread t2 = new Thread(() -> uc.increment());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
Q631 medium
When a single-dimensional array is passed as an argument to a method in Java, which passing mechanism is used?
Q632 medium code output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.*;
import java.util.Set;

public class Test {
    static class ItemDetails { @Min(1) public int price; public ItemDetails(int p) { this.price = p; } }
    static class Order {
        @Size(min=3) public String orderId;
        @Valid public ItemDetails item;
        public Order(String id, ItemDetails i) { this.orderId = id; this.item = i; }
    }
    public static void main(String[] args) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Order order = new Order("AB", new ItemDetails(0)); // orderId too short, item.price < 1
        Set<ConstraintViolation<Order>> violations = validator.validate(order);
        System.out.println("Violations: " + violations.size());
    }
}
Q633 medium
What is the primary purpose of the `@FunctionalInterface` annotation in Java?
Q634 medium code output
What is the content of 'data.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;

public class OverwriteTest {
    public static void main(String[] args) {
        try {
            FileWriter writer1 = new FileWriter("data.txt");
            writer1.write("First line.");
            writer1.close();
            FileWriter writer2 = new FileWriter("data.txt"); // Default is overwrite
            writer2.write("Second line.");
            writer2.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Q635 hard code output
What does this code print?
java
import java.util.Optional;
import java.util.function.Supplier;

public class LazyOptional {

    private static String expensiveOperation() {
        System.out.println("Performing expensive operation...");
        try { Thread.sleep(50); } catch (InterruptedException e) {}
        return "Default Value";
    }

    public static void main(String[] args) {
        Optional<String> presentOptional = Optional.of("Hello");
        Optional<String> emptyOptional = Optional.empty();

        System.out.println("Test 1: Optional is present with orElseGet");
        String value1 = presentOptional.orElseGet(() -> expensiveOperation());
        System.out.println("Value 1: " + value1);

        System.out.println("\nTest 2: Optional is empty with orElseGet");
        String value2 = emptyOptional.orElseGet(() -> expensiveOperation());
        System.out.println("Value 2: " + value2);

        System.out.println("\nTest 3: Optional is present with orElse");
        String value3 = presentOptional.orElse(expensiveOperation());
        System.out.println("Value 3: " + value3);

        System.out.println("\nTest 4: Optional is empty with orElse");
        String value4 = emptyOptional.orElse(expensiveOperation());
        System.out.println("Value 4: " + value4);
    }
}
Q636 medium
If an array `myArray` is declared as `int[] myArray = new int[5];`, which expression correctly accesses its last element?
Q637 medium code error
What is the compilation error in the provided Java code?
java
class ParentDisplay {
    public static void show() {
        System.out.println("Parent static show");
    }
}

class ChildDisplay extends ParentDisplay {
    @Override // ERROR: @Override on static method
    public static void show() {
        System.out.println("Child static show");
    }
}

public class Main {
    public static void main(String[] args) {
        ChildDisplay.show();
    }
}
Q638 hard code error
What compilation error will occur when compiling the following Java code?
java
import java.util.function.Supplier;

public class StaticLambdaThis {
    private int instanceField = 10;
    
    public static void main(String[] args) {
        Supplier<Integer> supplier = () -> this.instanceField;
        System.out.println(supplier.get());
    }
}
Q639 easy
Can a `private` method in a superclass be overridden in a subclass?
Q640 easy
Which `Iterator` method is used to check if there are more elements available for iteration?
← Prev 3031323334 Next → Page 32 of 200 · 3994 questions