☕ Java MCQ Questions – Page 184
Questions 3661–3680 of 3994 total — Java interview practice
▶ Practice All Java QuestionsIn highly constrained environments or low-level libraries, developers might consider creating custom `Error` subclasses instead of `Exception` subclasses. Under what specific, rare circumstances might creating a custom `Error` be justified over a custom `RuntimeException`?
What is the output of this code?
java
public class OperatorChallenge {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a + ", " + b);
}
}
What is the output of this code?
java
public class JoinInterruptTest {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
System.out.println("T1 started.");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("T1 interrupted!");
}
});
t1.start();
Thread.sleep(100);
try {
System.out.println("Main joining T1...");
Thread.currentThread().interrupt();
t1.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while joining!");
}
System.out.println("Main exiting.");
}
}
To compare two arrays, `array1` and `array2`, for element-by-element equality in Java, which method should be used?
What is the runtime error in the following Java code snippet?
java
import java.util.ArrayList;
public class Question9 {
public static void main(String[] args) {
ArrayList rawList = new ArrayList(); // Using raw type
rawList.add("Hello");
Integer val = (Integer) rawList.get(0);
System.out.println(val);
}
}
What error occurs when running this Java code?
java
import java.io.IOException;
public class FinallyBehavior {
public static void main(String[] args) {
try {
System.out.println("Inside try");
throw new IOException("Original IOException");
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} finally {
System.out.println("Inside finally");
throw new RuntimeException("Exception from finally");
}
}
}
What is the output of this Java code?
java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class QueueTest {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);
new Thread(() -> {
try {
queue.put(1);
System.out.println("Produced 1");
queue.put(2);
System.out.println("Produced 2");
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();
Thread.sleep(100);
new Thread(() -> {
try {
System.out.println("Consumed " + queue.take());
System.out.println("Consumed " + queue.take());
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();
Thread.sleep(500);
}
}
What is the output of this code?
java
class Parent {
public void foo() { System.out.print("Parent foo"); }
}
class Child extends Parent {
public void foo() { System.out.print("Child foo"); }
public void bar() { System.out.print("Child bar"); }
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
Child c = (Child) p;
c.bar();
}
}
What is the output of this Java code?
java
import java.util.function.Function;
public class MethodRefTest {
public static void main(String[] args) {
Function<String, Integer> parser = Integer::parseInt;
int result = parser.apply("123") + 10;
System.out.println(result);
}
}
Assuming `System.getProperty("user.dir")` is `/tmp/path_resolution_base` (or similar temporary path) and the file is created, what is the output of this Java code snippet?
java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class PathResolution {
public static void main(String[] args) throws IOException {
// Setup temporary directory structure for predictable results
Path tempDir = Files.createTempDirectory("path_resolution_base");
Path innerDir = Files.createDirectory(tempDir.resolve("inner"));
Path targetFile = Files.createFile(innerDir.resolve("data.txt"));
// File object constructed with '..' and '.'
File complexPathFile = new File(innerDir.toFile(), "../inner/./data.txt");
File actualFile = targetFile.toFile();
System.out.println("getPath(): " + complexPathFile.getPath().contains("../inner/./data.txt"));
System.out.println("getAbsolutePath() contains '..': " + complexPathFile.getAbsolutePath().contains(".."));
System.out.println("getCanonicalPath() matches actual: " + complexPathFile.getCanonicalPath().equals(actualFile.getCanonicalPath()));
Files.delete(targetFile);
Files.delete(innerDir);
Files.delete(tempDir);
}
}
When the `read()` method of a `FileReader` returns -1, what does it signify?
What error will occur when running this Java code, assuming the file 'data.ser' was successfully created previously by serializing an `Integer` object?
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("data.ser"))) {
String data = (String) ois.readObject(); // Assume data.ser contains an Integer
System.out.println("Deserialized: " + data);
} catch (IOException | ClassNotFoundException e) {
System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
What is the output of this Java code?
java
import java.util.TreeMap;
import java.util.NavigableMap;
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(30, "Thirty");
map.put(40, "Forty");
NavigableMap<Integer, String> head = map.headMap(20, true); // <= 20
NavigableMap<Integer, String> tail = map.tailMap(30, false); // > 30
NavigableMap<Integer, String> emptyTail = map.tailMap(50, false); // No keys > 50
System.out.println(head.keySet() + " " + tail.keySet() + " " + emptyTail.isEmpty());
}
}
What does this Java code snippet print to the console?
java
public class LoopTest {
public static void main(String[] args) {
int repeat = 0;
String message = "";
do {
message += "Java ";
repeat++;
} while (repeat < 2);
System.out.print(message);
}
}
Under what condition does a Java `while` loop continue its execution?
What error will this code produce?
java
public class LoopError {
public static void main(String[] args) {
int counter = 0;
for (int counter = 0; counter < 3; counter++) {
System.out.println(counter);
}
}
}
What is the result when compiling and running this Java code snippet?
java
import java.util.LinkedList;
import java.util.Queue;
public class QueueError {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.addFirst("Hello"); // Method 'addFirst' is not part of the Queue interface
}
}
Which method compares two strings for equality, ignoring case differences?
What is the output of this code?
java
public class StringTest {
public static void main(String[] args) {
String s = " Hello World ";
System.out.println(s.trim());
}
}
What does this Java code print, illustrating correct encapsulation using defensive copying in a getter?
java
import java.util.ArrayList;
import java.util.List;
class SecureData {
private final List<String> dataLines;
public SecureData(List<String> initialLines) {
this.dataLines = new ArrayList<>(initialLines);
}
public List<String> getDataLines() {
return new ArrayList<>(this.dataLines);
}
}
public class Main {
public static void main(String[] args) {
List<String> originalLines = new ArrayList<>(List.of("Line 1", "Line 2"));
SecureData data = new SecureData(originalLines);
System.out.println("Initial internal data: " + data.getDataLines());
List<String> retrievedLines = data.getDataLines();
retrievedLines.add("Line 3 - external");
System.out.println("Data after external modification attempt: " + data.getDataLines());
}
}