What is the primary purpose of the `synchronized` keyword in Java?
✅ Correct Answer: C) To ensure that only one thread can execute a critical section of code at a time.
The `synchronized` keyword provides mutual exclusion, ensuring that only one thread can execute a synchronized method or block for a given object (or class, for static methods) at any point in time, thereby preventing race conditions and ensuring data consistency.
Q2502mediumcode error
What is the compile-time error in the following Java code?
java
class MyClass {
int value;
public MyClass(int value) {
this.value = value;
}
private MyClass(int value) { // Duplicate signature with different access modifier
this.value = value * 2;
}
public static void main(String[] args) {
MyClass obj = new MyClass(10);
}
}
✅ Correct Answer: A) Error: constructor MyClass(int) is already defined in class MyClass
Constructors are identified by their signature, which consists of the class name and the parameter list. The access modifier (public, private, etc.) is not part of the signature. Having two constructors with the exact same parameter types (e.g., both `(int value)`) results in a 'duplicate constructor' compile-time error, regardless of their access modifiers.
Q2503hardcode output
What is the output of this code, given that `serializedData` was generated from a `MyObjectV1` class (an inner class used to simulate version 1 of `MyObject`) which had `serialVersionUID = 1L`?
java
import java.io.*;
class MyObject implements Serializable {
private static final long serialVersionUID = 2L; // Current version
String data = "Hello";
}
public class SerializationTest {
private static byte[] getSerializedDataFromV1() throws IOException {
class MyObjectV1 implements Serializable {
private static final long serialVersionUID = 1L; // Old version
String data = "Hello";
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(new MyObjectV1());
oos.close();
return bos.toByteArray();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
byte[] serializedData = getSerializedDataFromV1();
try (ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
ObjectInputStream ois = new ObjectInputStream(bis)) {
MyObject deserializedObj = (MyObject) ois.readObject();
System.out.println("Deserialized: " + deserializedObj.data);
} catch (InvalidClassException e) {
System.out.println("Error: " + e.getMessage().split(";")[0]);
}
}
}
✅ Correct Answer: A) Error: MyObject; local class incompatible
Attempting to deserialize an object with a 'serialVersionUID' of 1L using a class definition that has a 'serialVersionUID' of 2L results in an `InvalidClassException` due to the mismatch. The exception message indicates the incompatible local class.
Q2504hardcode output
What does this code print?
java
String text = " Hello World ";
text.trim().replace("o", "X").toLowerCase();
System.out.println(text);
✅ Correct Answer: A) Hello World
Java `String` objects are immutable. The methods `trim()`, `replace()`, and `toLowerCase()` all return new `String` objects with the modified content. Since the result of the method chain is not assigned back to the `text` variable, `text` retains its original value.
Q2505hardcode error
What is the most likely error when executing this Java code snippet?
✅ Correct Answer: B) Initialization Error: java.lang.NullPointerException
The `BufferedWriter` constructor expects a non-null `Writer` instance. Passing `null` will cause a `NullPointerException` during the construction of `BufferedWriter`.
Q2506hardcode error
What is the compile-time error in the following Java code?
java
public class FloatingPointTest {
public static void main(String[] args) {
float piValue = 3.1415926535; // Double literal assigned to float
System.out.println(piValue);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from double to float
Floating-point literals without a suffix are by default of type 'double'. Assigning a 'double' literal to a 'float' variable requires an explicit cast or appending 'f'/'F' to the literal, as it represents a possible lossy conversion.
Q2507easycode output
What does this Java code print?
java
public class ImmutableTest {
public static void main(String[] args) {
String s = "Hello";
s.concat(" World");
System.out.println(s);
}
}
✅ Correct Answer: A) Hello
String objects in Java are immutable. The `concat()` method returns a new String object with the concatenated value, but it does not modify the original `s` reference. Since the return value is not assigned back to `s`, the original value remains.
Q2508easy
`BufferedWriter` typically wraps which type of stream?
✅ Correct Answer: D) A `Writer`
`BufferedWriter` is a character-output stream that is designed to wrap another `Writer` object, such as a `FileWriter` or `OutputStreamWriter`, to provide buffering.
Q2509easycode error
What compile-time error will occur in the `main` method?
java
class MyClass {
private MyClass() {
System.out.println("Private Constructor");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass(); // Attempting to instantiate a private constructor
}
}
✅ Correct Answer: A) MyClass() has private access in MyClass
A private constructor cannot be accessed or invoked from outside the class it is declared in. Attempting to instantiate the class externally will result in a compile-time access error.
Q2510medium
If a `BufferedWriter` is closed without explicitly calling `flush()`, what happens to any data still residing in its internal buffer?
✅ Correct Answer: A) The data is automatically written to the underlying stream/file by the JVM.
The `close()` method of `BufferedWriter` implicitly calls `flush()` before closing the stream. Therefore, any data remaining in the buffer will be written to the underlying writer/file before the resources are released.
Q2511mediumcode output
What is the output of the following code?
java
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abcdefg");
String sub1 = sb.substring(2);
String sub2 = sb.substring(1, 4);
System.out.print(sub1 + " " + sub2);
}
}
✅ Correct Answer: A) cdefg bcd
`sb.substring(2)` extracts from index 2 to the end, resulting in "cdefg". `sb.substring(1, 4)` extracts from index 1 (inclusive) to 4 (exclusive), resulting in "bcd". The output concatenates these with a space.
Q2512easy
Which of the following is NOT considered a common component of a Java class definition?
✅ Correct Answer: D) Threads
While classes can define and manage threads, threads themselves are not intrinsic structural components of a class definition, unlike fields, methods, and constructors.
Q2513mediumcode output
What is the output of this Java code?
java
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
TreeSet<String> letters = new TreeSet<>();
letters.add("B");
letters.add("A");
letters.add("D");
letters.add("C");
letters.add("E");
String first = letters.pollFirst();
String last = letters.pollLast();
System.out.println(first + ", " + last + ", " + letters);
}
}
✅ Correct Answer: A) A, E, [B, C, D]
`pollFirst()` retrieves and removes the lowest element (A), and `pollLast()` retrieves and removes the highest element (E). The `TreeSet` then prints the remaining sorted elements.
Q2514easy
If a class has a `private final` field that holds a reference to a mutable object (e.g., an `ArrayList`), is the class guaranteed to be immutable?
✅ Correct Answer: B) No, because the referenced mutable object's state can still be changed.
While the reference to the `ArrayList` cannot be changed (`final`), the `ArrayList` object itself is mutable. Its contents can still be modified, thus the containing class is not truly immutable without defensive copying.
Q2515hard
Consider a complex `if` condition: `if (methodA() || (methodB() && methodC()))`. If `methodA()` returns `true`, what is the guaranteed execution behavior of `methodB()` and `methodC()`?
✅ Correct Answer: A) Neither `methodB()` nor `methodC()` will be executed due to short-circuiting.
Due to the short-circuiting `||` operator, if the left operand (`methodA()`) evaluates to `true`, the entire `||` expression is true, and the right operand (`(methodB() && methodC())`) is not evaluated.
Q2516hardcode output
What is the output of this code?
java
public class StringInternTest {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";
String s3 = s1.intern();
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}
✅ Correct Answer: B) false
true
s1 is created in the heap, s2 is from the string pool. s1 == s2 is false. s1.intern() adds "hello" to the string pool (if not already present) and returns its reference, which is the same as s2. So s2 == s3 is true.
Q2517hard
Which statement best describes the atomicity of operations performed by the `java.io.File` class methods in relation to concurrent access by multiple threads or processes?
✅ Correct Answer: A) Most `File` operations are not atomic; for example, checking `exists()` then calling `delete()` can lead to a race condition where another process creates the file between these two calls.
The `java.io.File` API generally does not provide atomic operations, meaning a sequence of calls like `exists()` followed by `delete()` is susceptible to race conditions in a concurrent environment. External synchronization or using NIO.2's atomic methods might be necessary.
Q2518easycode output
What is the output of this code?
java
import java.io.BufferedWriter;
import java.io.StringWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
StringWriter stringWriter = new StringWriter();
try (BufferedWriter writer = new BufferedWriter(stringWriter)) {
writer.write("PartA");
writer.flush();
writer.write("PartB");
writer.flush();
System.out.print(stringWriter.toString());
} catch (IOException e) {
System.out.print("Error");
}
}
}
✅ Correct Answer: A) PartAPartB
Each `write()` call adds data to the buffer, and each `flush()` call writes the current buffered content to the underlying `StringWriter`. Subsequent writes append to the existing content.
Q2519medium
What is the fundamental principle behind the execution of intermediate operations in the Java Stream API?
✅ Correct Answer: B) Lazy execution, where operations are deferred until a terminal operation is invoked.
Intermediate operations are lazy; they only record the transformations to be performed. The actual processing of elements occurs only when a terminal operation is called.
Q2520hard
What is the specific contract of `java.io.File.createNewFile()` regarding its return value and underlying file system operations, particularly in a multi-threaded or concurrent environment?
✅ Correct Answer: A) It atomically creates a new, empty file if and only if a file with the same name does not already exist, returning `true` on success and `false` if the file already existed.
`createNewFile()` is designed to be atomic with respect to the file's existence, ensuring that if it returns `true`, the calling thread successfully created the file and no other thread created it simultaneously. It returns `false` if the file already existed.