☕ Java MCQ Questions – Page 43
Questions 841–860 of 3994 total — Java interview practice
▶ Practice All Java QuestionsA Java Lambda Expression can only be used to implement which type of interface?
What is the runtime error encountered when executing this Java code snippet?
java
import java.util.HashSet;
import java.util.Objects;
class GuardedKey {
String id;
public GuardedKey(String id) { this.id = id; }
@Override
public int hashCode() {
if (id == null) {
throw new IllegalArgumentException("ID cannot be null for hashing.");
}
return id.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GuardedKey that = (GuardedKey) o;
return Objects.equals(id, that.id);
}
}
public class Main {
public static void main(String[] args) {
HashSet<GuardedKey> set = new HashSet<>();
set.add(new GuardedKey(null)); // Adding an object with null ID
}
}
What type of error will occur when executing the following Java code?
java
public class Main {
public static void main(String[] args) {
Integer i = null;
int j = i;
System.out.println(j);
}
}
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.Size;
import java.util.Set;
public class Test {
static class Detail {
@Size(min=5) public String code;
public Detail(String code) { this.code = code; }
}
static class Product {
@Valid public Detail detail;
public Product(Detail d) { this.detail = d; }
}
public static void main(String[] args) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Product p = new Product(new Detail("abc")); // code length < 5
Set<ConstraintViolation<Product>> violations = validator.validate(p);
System.out.println("Violations: " + violations.size());
}
}
What compile-time error will occur when compiling this Java code?
java
public class DataTypeByteError {
public static void main(String[] args) {
byte b = 130;
System.out.println(b);
}
}
What does this code print?
java
public class DataTypeTest {
public static void main(String[] args) {
float temperature = 25.5f;
System.out.println(temperature);
}
}
What is the output of this Java code snippet, assuming it runs on a Unix-like system where symbolic link creation is successful and the current process has sufficient permissions?
java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class SymlinkTest {
public static void main(String[] args) throws IOException {
Path tempDir = Files.createTempDirectory("symlink_test");
Path targetFile = Files.createFile(tempDir.resolve("target.txt"));
Path symlinkFile = tempDir.resolve("link.txt");
Files.createSymbolicLink(symlinkFile, targetFile.getFileName()); // Relative link
File targetObj = targetFile.toFile();
File symlinkObj = symlinkFile.toFile();
System.out.println("Symlink exists: " + symlinkObj.exists());
System.out.println("Symlink isFile: " + symlinkObj.isFile());
System.out.println("Symlink getCanonicalPath equals Target canonicalPath: " + symlinkObj.getCanonicalPath().equals(targetObj.getCanonicalPath()));
Files.delete(symlinkFile);
Files.delete(targetFile);
Files.delete(tempDir);
}
}
What is the only ternary (three-operand) operator in Java?
Is `TreeSet` thread-safe?
What is the output of this code snippet at 'Waiter state 2'?
java
public class ThreadStateDemo5 {
private static final Object monitor = new Object();
private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread waiter = new Thread(() -> {
synchronized (monitor) {
try { while (!flag) { monitor.wait(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
System.out.println("Waiter: Notified!");
});
Thread notifier = new Thread(() -> {
try { Thread.sleep(100); synchronized (monitor) { flag = true; monitor.notify(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
waiter.start();
Thread.sleep(50); // Ensure waiter enters wait()
notifier.start();
Thread.sleep(50); // Give notifier time to run and notify
System.out.println("Waiter state 2: " + waiter.getState());
Thread.sleep(200); // Allow threads to complete
}
}
What is the compile-time error in this Java code?
java
class ConcreteProcessor {
public abstract void performAction();
public void run() {
System.out.println("Processor running.");
}
}
What error occurs when `notify()` is called on an object without holding the object's lock?
java
public class Main {
public static void main(String[] args) {
Object lock = new Object();
lock.notify(); // Calling notify() outside a synchronized block
}
}
What error will occur when this Java code attempts to deserialize, assuming 'missing.ser' does not exist?
java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("missing.ser"))) {
Object obj = ois.readObject();
System.out.println("Object deserialized.");
} catch (IOException | ClassNotFoundException e) {
System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
What does this code print?
java
public class WaitNotifySpurious {
private final Object lock = new Object();
private int resource = 0;
public void consume() {
synchronized (lock) {
while (resource == 0) { // Essential while loop
try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
resource--;
System.out.println(Thread.currentThread().getName() + " consumed. Resource: " + resource);
}
}
public void produce() {
synchronized (lock) {
resource++;
System.out.println(Thread.currentThread().getName() + " produced. Resource: " + resource);
lock.notify(); // Only one thread is notified
}
}
public static void main(String[] args) throws InterruptedException {
WaitNotifySpurious test = new WaitNotifySpurious();
Thread c1 = new Thread(test::consume, "Consumer-1");
Thread c2 = new Thread(test::consume, "Consumer-2");
Thread p1 = new Thread(test::produce, "Producer-1");
c1.start(); c2.start();
Thread.sleep(100); // Ensure consumers wait first
p1.start();
Thread.sleep(500); // Allow time for operations
System.out.println("Final resource: " + test.resource);
}
}
What is the output of this code snippet?
java
public class Main {
public static void main(String[] args) {
int val1 = 10;
int val2 = 10;
System.out.println(val1 == val2);
}
}
What error occurs when compiling this Java code?
java
import java.io.IOException;
class Parent {
public void method() throws IOException {
System.out.println("Parent method");
}
}
class Child extends Parent {
@Override
public void method() throws Exception { // Attempting to declare a broader exception
System.out.println("Child method");
}
}
What is the primary architectural limitation of `FileReader` that often leads to recommendations against its direct use for robust, portable applications?
What is the compile-time error in this Java code?
java
abstract class MyService {
public static abstract void init();
public void start() {
System.out.println("Service starting...");
}
}
What is the output of this code?
java
class Vehicle {
void honk() {
System.out.println("Vehicle honks");
}
}
class Car extends Vehicle {
void honk() {
super.honk();
System.out.println("Car honks");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
}
}
What is the result of assigning a `byte` variable to an `int` variable in Java?