☕ Java MCQ Questions – Page 144
Questions 2861–2880 of 3994 total — Java interview practice
▶ Practice All Java QuestionsIf a functional interface has a single abstract method with the signature `void process(String message)`, which of the following method references would be compatible?
What is the compile-time error in this Java code?
java
public class Test {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 3:
System.out.println("Wednesday");
continue;
case 5:
System.out.println("Friday");
break;
}
}
}
Which of the following scenarios is a `do-while` loop particularly well-suited for in Java?
What error will occur when compiling this Java code?
java
public class ConditionCheck {
public static void main(String[] args) {
int value = 10;
if (value > 5);
{
System.out.println("Value is greater than 5.");
}
else {
System.out.println("Value is 5 or less.");
}
}
}
What is the runtime error when the `main` method is executed?
java
class MyCustomException extends Exception {
public MyCustomException(String message) { super(message); }
}
public class Main {
public static MyCustomException createNullException() {
return null;
}
public static void main(String[] args) {
MyCustomException e = createNullException();
throw e; // This line attempts to throw a null reference, causing a runtime error
}
}
What is the output of this Java code?
java
import java.io.*;
class MySimpleObject implements Serializable {
String data;
public MySimpleObject(String data) { this.data = data; }
}
public class DeserializationError9 {
public static void main(String[] args) {
byte[] fullData = null;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(new MySimpleObject("Complete"));
fullData = bos.toByteArray();
} catch (IOException e) { e.printStackTrace(); }
// Create a truncated byte array
byte[] truncatedData = new byte[fullData.length / 2];
System.arraycopy(fullData, 0, truncatedData, 0, truncatedData.length);
try (ByteArrayInputStream bis = new ByteArrayInputStream(truncatedData);
ObjectInputStream ois = new ObjectInputStream(bis)) {
MySimpleObject obj = (MySimpleObject) ois.readObject();
System.out.println("Deserialized: " + obj.data);
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + ": " + e.getMessage());
}
}
}
What error occurs when compiling this code, assuming 'data.txt' exists?
java
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MyClass {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("data.txt");
int charCode = reader.read(); // Potential IOException here
System.out.println("Character read: " + (char)charCode);
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Error closing reader: " + e.getMessage());
}
}
}
}
}
When performing a large number of `String` concatenations in a loop (e.g., `str = str + char;`), which approach is generally recommended for better performance?
What is the compile-time error in the following Java code snippet?
java
public class SwitchBlockNoYieldError {
public static void main(String[] args) {
int x = 1;
String result = switch (x) {
case 1 -> {
System.out.println("Case 1 executed"); // Error expected here
}
case 2 -> {
System.out.println("Case 2 executed");
yield "Two";
}
default -> "Other";
};
System.out.println(result);
}
}
What compilation error occurs in this Java code due to encapsulation rules for final fields?
java
class Coordinate {
private final int x;
public Coordinate() {
// x = 0; // Missing initialization
}
}
public class Map {
public static void main(String[] args) {
Coordinate point = new Coordinate();
}
}
What is the output of this code?
java
import java.io.File;
import java.io.IOException;
public class RestrictedDirectoryFileCreation {
public static void main(String[] args) {
File restrictedDir = new File("restricted_test_dir");
File newFile = new File(restrictedDir, "new_restricted_file.txt");
try {
restrictedDir.mkdir();
// Make directory unwritable for everyone
restrictedDir.setWritable(false, false);
System.out.println("Directory writable: " + restrictedDir.canWrite());
// Attempt to create a file in a non-writable directory
boolean created = newFile.createNewFile();
System.out.println("File created: " + created);
} catch (IOException e) {
System.out.println("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage());
} finally {
// Cleanup: Need to make it writable again to delete contents and directory
restrictedDir.setWritable(true, false);
newFile.delete();
restrictedDir.delete();
}
}
}
What are the default values for elements in a newly declared `int[][] myMatrix = new int[2][3];` if no explicit values are assigned?
What is the output of this code?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add("London");
cities.add("Paris");
StringBuilder result = new StringBuilder();
for (String city : cities) {
result.append(city).append(" ");
}
System.out.println(result.toString().trim());
}
}
What error will this code produce?
java
public class LoopError {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
What is the compilation error in the following code?
java
class A {
protected void printMessage() {
System.out.println("Hello from A");
}
}
class B extends A {
@Override
private void printMessage() {
System.out.println("Hello from B");
}
}
When an unlabeled `continue` statement is encountered within the innermost loop of a nested loop structure, what does it do?
What will be the output when executing this Java program that attempts to manage immutability for a list?
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class ImmutableConfig {
private final List<String> items;
public ImmutableConfig(List<String> items) {
this.items = Collections.unmodifiableList(new ArrayList<>(items)); // Defensive copy
}
public List<String> getItems() {
return items; // Returns the unmodifiable list directly
}
}
public class ImmutableWrapperError {
public static void main(String[] args) {
List<String> mutableSource = new ArrayList<>();
mutableSource.add("Setting1");
ImmutableConfig config = new ImmutableConfig(mutableSource);
config.getItems().add("Setting2"); // Attempt to modify through getter
}
}
Which of the following is true about a mutable object in Java?
What is the average time complexity for `get()` and `put()` operations in a Java HashMap?
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String element = it.next();
if (element.equals("B")) {
list.remove(element);
}
}
System.out.println(list);
}
}