In Java, a "jagged array" is a multidimensional array where inner arrays can have different lengths. Which statement accurately describes the memory representation of an `int[][]` jagged array?
✅ Correct Answer: B) It is an array of references, where each reference points to a separate one-dimensional array object, which can vary in length.
A multidimensional array in Java is an array of arrays. For a jagged array, the outer array holds references, and each reference can point to a distinct 1D array object, allowing variable lengths and non-contiguous memory for inner arrays.
Q1122hard
How does the behavior of `java.io.File.listRoots()` typically differ between a Windows operating system and a Unix-like operating system (e.g., Linux or macOS)?
✅ Correct Answer: A) On Windows, it returns an array of File objects representing drive letters (e.g., `C:\`, `D:\`), while on Unix-like systems, it returns a single File object representing the filesystem root (`/`).
`listRoots()` provides an array of File objects representing the available filesystem roots. On Windows, these are typically drive letters; on Unix-like systems, it's typically just the root directory `/`.
Q1123mediumcode error
What is the compilation error for the provided Java code?
java
public class InstanceofError {
public static void main(String[] args) {
int x = 10;
if (x instanceof Integer) {
System.out.println("x is an Integer object.");
}
}
}
✅ Correct Answer: B) Cannot use 'instanceof' with primitive type 'int'
The `instanceof` operator is used to check if an object is an instance of a particular class or interface. It cannot be used with primitive types like `int`, leading to a compile-time error.
Q1124easy
Which method returns the character at a specified index within the string?
✅ Correct Answer: C) charAt(int index)
The `charAt()` method returns the character located at the specified index in the string.
Q1125medium
What is a key difference in execution guarantee between a `do-while` loop and a `while` loop in Java?
✅ Correct Answer: A) A `do-while` loop's body is guaranteed to execute at least once, regardless of the condition.
This is the defining characteristic of a `do-while` loop; its condition is checked after the first iteration, ensuring at least one execution.
Q1126easycode error
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
import java.io.IOException;
public class FileError5 {
public static void main(String[] args) throws IOException {
File existingFile = new File("temp.txt");
existingFile.createNewFile(); // Assuming this succeeds
File newFile = new File(existingFile, "child.txt");
newFile.createNewFile();
System.out.println("Child file path: " + newFile.getAbsolutePath());
}
}
✅ Correct Answer: B) An IOException will be thrown because `existingFile` is a file, not a directory, so it cannot be a parent.
The `File(File parent, String child)` constructor expects the `parent` `File` object to represent a directory. If `existingFile` is a regular file, attempting to create `child.txt` relative to it will result in an `IOException` stating that the parent path is not a directory.
Q1127hardcode output
What is the output of this code snippet?
java
import java.util.concurrent.atomic.AtomicInteger;
public class SharedCounterTest {
private static final AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Runnable incrementTask = () -> {
for (int i = 0; i < 50000; i++) {
counter.incrementAndGet();
}
};
Thread t1 = new Thread(incrementTask);
Thread t2 = new Thread(incrementTask);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final counter: " + counter.get());
}
}
✅ Correct Answer: A) Final counter: 100000
The `AtomicInteger` class provides atomic operations for integer values, guaranteeing thread-safe increments. Despite concurrent access from two threads, each increment operation is indivisible, ensuring the final count is exactly 100000.
Q1128hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Start");
String nullString = null;
sb.append(" ").append(nullString).append(" End");
System.out.println(sb);
}
}
✅ Correct Answer: A) Start null End
When `append(String)` is called with a `null` String reference, the literal string "null" is appended to the StringBuilder, not a null character or a `NullPointerException`.
Q1129mediumcode output
What is the final output of 'Final Count'?
java
import java.util.concurrent.Semaphore;
public class Main {
private static Semaphore semaphore = new Semaphore(1);
private static int count = 0;
public static void performTask() {
try {
semaphore.acquire();
for (int i = 0; i < 500; i++) {
count++;
}
System.out.println(Thread.currentThread().getName() + " finished. Count: " + count);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
semaphore.release();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(Main::performTask, "Thread-1");
Thread t2 = new Thread(Main::performTask, "Thread-2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + count);
}
}
✅ Correct Answer: A) Final Count: 1000
The `Semaphore` initialized with 1 permit ensures that only one thread can execute the `performTask` critical section at a time. This effectively serializes the increment operations, guaranteeing that the `count` variable is correctly updated by both threads to 500 + 500 = 1000.
Q1130easycode error
What is the compile-time error in the following Java code?
java
class Calculator {
void add(int a, int b) {
// Does something
}
int add(int a, int b) {
return a + b;
}
}
✅ Correct Answer: A) Compile-time error: Method 'add(int, int)' is already defined in 'Calculator'.
Method overloading in Java requires a difference in the number or type of parameters, not just the return type. Defining two methods with the exact same name and parameter list, even with different return types, results in a compile-time error indicating the method is already defined.
Q1131medium
What is the primary effect of calling `Thread.yield()`?
✅ Correct Answer: C) It suggests to the scheduler that the current thread is willing to yield its current use of a processor.
`Thread.yield()` is a hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint, and it does not release any acquired locks.
Q1132easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("X is greater than 5");
} else System.out.println("X is 5 or less");
else {
System.out.println("This is an extra else");
}
}
}
✅ Correct Answer: B) Compile-time Error: 'else' without 'if'.
An 'else' statement must directly follow an 'if' or an 'else if' block. Having a second 'else' without an intervening 'if' results in a compile-time error because it has no corresponding 'if'.
Q1133hardcode output
What is the output of this code?
java
class A {
private void display() {
System.out.println("Class A display");
}
public void show() {
display();
}
}
class B extends A {
public void display() {
System.out.println("Class B display");
}
}
public class Main {
public static void main(String[] args) {
A obj = new B();
obj.show();
}
}
✅ Correct Answer: A) Class A display
Private methods cannot be overridden as they are not inherited. The `display()` method in class `B` is a completely new method. When `show()` is called on `obj` (of compile-time type `A`), it invokes `A`'s own private `display()` method.
Q1134easy
How can you open a `FileWriter` to append data to an existing file instead of overwriting it?
✅ Correct Answer: B) Use `new FileWriter("filename.txt", true)`
The `FileWriter` constructor that takes a `String` filename and a boolean `append` flag set to `true` allows data to be added to the end of the file.
Q1135mediumcode error
What will be the compilation error in this code?
java
class Base {
public int calculate() {
return 10;
}
}
class Derived extends Base {
@Override
public double calculate() {
return 20.0;
}
}
✅ Correct Answer: A) Error: incompatible return type: double cannot be converted to int
For primitive return types, an overridden method must have the exact same return type as the method in the superclass. Changing 'int' to 'double' is not allowed.
Q1136hardcode error
What is the compile-time error in the `Circle` class?
java
class Shape {
public void draw(int size) {
System.out.println("Drawing Shape of size " + size);
}
}
class Circle extends Shape {
@Override
public void draw(double radius) { // Line 8
System.out.println("Drawing Circle with radius " + radius);
}
}
public class Canvas {
public static void main(String[] args) {
Shape s = new Circle();
s.draw(10);
}
}
✅ Correct Answer: A) The `draw` method in `Circle` has a different parameter type, making it an overload, not an override.
For a method to correctly override another, it must have the exact same signature (method name and parameter types). Changing the parameter type from `int` to `double` makes it an overloaded method, not an override, causing a compile-time error on Line 8 with `@Override`.
Q1137hard
Consider the `read(char[] cbuf, int off, int len)` method of `FileReader`. If `len` is specified as 0, what is the guaranteed return value, assuming the stream is open and valid?
✅ Correct Answer: A) 0, and no characters are read into the buffer.
If the `len` argument is zero, then no characters are read, and `0` is returned. This is specified behavior for many `read` methods in Java I/O streams when `len` is 0.
Q1138hardcode output
What is the output of this code?
java
class InitialException extends Exception { public InitialException(String msg) { super(msg); } }
class WrappedException extends Exception { public WrappedException(String msg, Throwable c) { super(msg, c); } }
class FinallyException extends RuntimeException { public FinallyException(String msg) { super(msg); } }
public class Main {
public static void foo() throws InitialException { throw new InitialException("Original problem"); }
public static void bar() throws WrappedException {
try { foo(); }
catch (InitialException e) { System.out.println("Caught in bar: " + e.getMessage()); throw new WrappedException("Wrapped original", e); }
finally { System.out.println("Finally in bar"); throw new FinallyException("Finally block issue"); }
}
public static void main(String[] args) {
try { bar(); }
catch (Throwable t) { System.out.println("Caught in main: " + t.getClass().getSimpleName() + ": " + t.getMessage()); }
}
}
✅ Correct Answer: A) Caught in bar: Original problem
Finally in bar
Caught in main: FinallyException: Finally block issue
When an exception is thrown from both a `catch` block and a `finally` block, the exception thrown by the `finally` block is the one that propagates out of the method. The `WrappedException` is effectively suppressed by `FinallyException`.
Q1139medium
Which of the following is a key functional difference between `java.util.HashMap` and `java.util.Hashtable`?
✅ Correct Answer: C) `Hashtable` is a legacy class that is synchronized, while `HashMap` is unsynchronized.
`Hashtable` is a legacy, synchronized class that does not permit null keys or values. `HashMap` is a modern, unsynchronized class that allows one null key and multiple null values, generally offering better performance in single-threaded environments.
Q1140mediumcode output
What is the output of this Java program?
java
class FinallyThrow {
public static void main(String[] args) {
try {
System.out.println("Entering try");
throw new RuntimeException("Exception from try");
} catch (Exception e) {
System.out.println("Catching: " + e.getMessage());
throw new IllegalArgumentException("Rethrown from catch");
} finally {
System.out.println("Entering finally");
throw new IllegalStateException("Exception from finally");
}
}
}
✅ Correct Answer: A) Entering try
Catching: Exception from try
Entering finally
Exception in thread "main" java.lang.IllegalStateException: Exception from finally
When an exception is thrown in a `finally` block, it takes precedence over any pending exception (like the one rethrown from the `catch` block) or a normal return. The output will include messages from try/catch/finally, and then the program terminates with the `IllegalStateException`.