☕ Java MCQ Questions – Page 100
Questions 1981–2000 of 3994 total — Java interview practice
▶ Practice All Java QuestionsWhat is the output of this code?
java
public class Main {
public static void main(String[] args) {
System.out.print("Start ");
try {
System.out.print("Inside Try ");
} finally {
System.out.print("Inside Finally ");
}
System.out.print("End ");
}
}
What is the output of this Java code snippet?
java
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File file = new File("myFile.txt");
System.out.println(file.isAbsolute());
}
}
What is the output of this Java code snippet?
java
class Person {
String name;
public Person(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("Alice");
Person p2 = new Person("Bob");
System.out.print(p1.name + " and " + p2.name);
}
}
Consider an immutable class `MyImmutableClass` that holds a `private final Map<String, String> internalMap;`. Which of the following is the most robust way to ensure that the `internalMap` remains immutable even when accessed via a getter?
Which method is used to add a sequence of characters to the end of an existing `StringBuffer` object?
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
int[][] grid = new int[2][3];
grid[0][0] = 5;
grid[1][2] = 10;
System.out.println(grid[0][0] + grid[1][0]);
}
}
What is the compilation error in the following Java code?
java
public class TypeMismatch {
public static void main(String[] args) {
int count = "ten";
System.out.println(count);
}
}
What is the error encountered when compiling this Java code?
java
import java.util.List;
public class GenericArrayError<T> {
T[] createArray(int size) {
return new T[size];
}
public static void main(String[] args) {
GenericArrayError<String> creator = new GenericArrayError<>();
String[] strArray = creator.createArray(5);
}
}
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 FileWriterImplicitFlush {
public static void main(String[] args) {
String filename = "implicit_flush_test.txt";
try {
FileWriter fw = new FileWriter(filename);
fw.write("Hello FileWriter");
fw.close();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = br.readLine();
System.out.println(line != null ? line : "[Empty]");
}
} catch (IOException e) { System.out.println("Error: " + e.getMessage());
} finally { try { Files.deleteIfExists(Path.of(filename)); } catch (IOException ignored) {} }
}
}
Conceptually, how does a HashMap store its entries to handle collisions?
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
public class FileError6 {
public static void main(String[] args) {
File file = null;
if (args.length > 0) {
file = new File(args[0]);
}
file.delete(); // Potentially problematic line
System.out.println("Operation attempted.");
}
}
What is the result of executing this Java code snippet?
java
public class PrimitiveArrayCast {
public static void main(String[] args) {
int[] intArray = {1, 2, 3};
Object[] objArray = (Object[]) intArray;
System.out.println("Array cast successful");
}
}
What is the output of this code?
java
import java.io.File;
import java.io.IOException;
public class PathResolution {
public static void main(String[] args) throws IOException {
File file = new File("./temp_data/../my_document.pdf");
System.out.println(file.getAbsolutePath().contains("..") + ", " + file.getCanonicalPath().contains(".."));
}
}
What is the final output of this code, specifically the `Barrier reached` lines and `sharedCounter` values?
java
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
private final CyclicBarrier barrier;
private int sharedCounter = 0;
public CyclicBarrierTest() {
this.barrier = new CyclicBarrier(3, () -> {
System.out.println("Barrier reached! All threads arrived. Counter: " + sharedCounter);
sharedCounter = 0; // Reset for next phase
});
}
public void worker(String name) {
try {
Thread.sleep(50); synchronized(this){ sharedCounter++; } barrier.await();
Thread.sleep(50); synchronized(this){ sharedCounter++; } barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
CyclicBarrierTest test = new CyclicBarrierTest();
for (int i = 0; i < 3; i++) {
new Thread(() -> test.worker("Worker-" + i)).start();
}
Thread.sleep(1000); // Allow time for all phases
}
}
What is the output of the following Java program?
java
public class TryCatchFinallyFlow {
public static void main(String[] args) {
try {
System.out.println("1. Inside try");
throw new RuntimeException("Test Exception");
} catch (RuntimeException e) {
System.out.println("2. Inside catch: " + e.getMessage());
} finally {
System.out.println("3. Inside finally");
}
System.out.println("4. After blocks");
}
}
Which statement accurately describes a key difference between abstract classes and interfaces in Java (post-Java 8)?
Assume a file named 'empty.txt' exists but contains no characters (it's an empty file). What does this code print?
java
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
public class EmptyFileRead {
public static void main(String[] args) throws IOException {
// Assume 'empty.txt' is an empty file
StringBuilder sb = new StringBuilder();
int c = 0; // Initialize c outside the try-with-resources
try (FileReader reader = new FileReader(new File("empty.txt"))) {
while ((c = reader.read()) != -1) {
sb.append((char) c);
}
if (sb.length() == 0) {
sb.append("Empty");
} else {
sb.append("Not Empty");
}
sb.append(" - Read value after loop: " + c);
}
System.out.println(sb.toString());
}
}
What is the compile-time or runtime error in the following Java code snippet when attempting to deserialize the object?
java
import java.io.*;
class DataHolder implements Externalizable {
private int value1;
private String value2;
public DataHolder() {} // Required public no-arg constructor
public DataHolder(int value1, String value2) {
this.value1 = value1;
this.value2 = value2;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(value1); // Only writing value1
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.value1 = in.readInt();
this.value2 = in.readUTF(); // Trying to read value2 which was not written
}
}
public class SerializationQuestion7 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
DataHolder data = new DataHolder(10, "Hello");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"))) {
oos.writeObject(data);
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"))) {
DataHolder loadedData = (DataHolder) ois.readObject();
}
}
}
What is the primary guarantee provided by the `volatile` keyword in Java?
When using `Object.wait()` in Java for inter-thread communication, why is it crucial to always invoke `wait()` within a `while` loop instead of an `if` statement?