Consider the expression: `(true ? 10 : 20.0)`. What is the type of the result?
✅ Correct Answer: B) double
The Java ternary operator's result type is determined by type promotion rules. If the second and third operands have different types, the result type is the wider type that both can be promoted to, which is `double` for `int` and `double`.
Q1822easycode error
What is the result of running this Java code?
java
public class StringError {
public static void main(String[] args) {
String s1 = null;
String s2 = "test";
System.out.println(s1.equals(s2));
}
}
✅ Correct Answer: C) java.lang.NullPointerException
Calling the equals() method on a null String reference (s1) will throw a NullPointerException at runtime. While equals() can handle a null argument, it cannot be invoked on a null object itself.
Q1823easycode error
What is the error in this code?
java
// import java.util.TreeMap; // This line is missing
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap<>();
map.put("key", "value");
System.out.println(map.size());
}
}
✅ Correct Answer: A) Compilation Error: cannot find symbol class TreeMap
The `TreeMap` class is part of the `java.util` package and must be explicitly imported using `import java.util.TreeMap;`. Without this import statement, the compiler cannot find the `TreeMap` symbol, resulting in a compilation error.
Q1824easycode error
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
public class FileError2 {
public static void main(String[] args) {
File file = new File("existingFile.txt");
try {
file.createNewFile(); // Ensure file exists for the next step
File[] files = file.listFiles();
System.out.println(files[0].getName());
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: B) A NullPointerException will be thrown at runtime because `listFiles()` returns null for a file.
The `listFiles()` method returns `null` if the `File` object does not denote a directory. Attempting to access `files[0]` on a null array will result in a `NullPointerException`.
Q1825hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
try {
System.out.print("Try ");
System.exit(0);
} catch (Exception e) {
System.out.print("Catch ");
} finally {
System.out.print("Finally ");
}
System.out.print("End");
}
}
✅ Correct Answer: A) Try
The `System.exit(0)` call terminates the JVM immediately. This prevents the `finally` block from executing, as well as any code following the `try-catch-finally` construct.
Q1826mediumcode error
What error will this Java code produce?
java
public class ArrayError {
public static void main(String[] args) {
int[][] matrix = new int[2][2];
matrix[0] = 10;
System.out.println(matrix[0][0]);
}
}
✅ Correct Answer: A) Compile-time error: incompatible types: int cannot be converted to int[]
The element `matrix[0]` is of type `int[]` (an integer array), but the code attempts to assign an `int` (the primitive value `10`) to it. This is a type mismatch that causes a compile-time error.
✅ Correct Answer: A) Main thread interrupted status (before sleep): true
Main thread: Caught InterruptedException.
Main thread interrupted status (after catch): false
Main thread: Exiting.
When the main thread's interrupted status is set to `true`, a subsequent call to `Thread.sleep()` will immediately throw an `InterruptedException`. Crucially, when `InterruptedException` is thrown, the interrupted status of the thread is cleared (set back to `false`).
Q1828medium
If a thread calls `object.wait()` within a synchronized block without a timeout, what state does the thread enter, assuming no `notify()` call occurs immediately?
✅ Correct Answer: C) WAITING
Calling `object.wait()` without a timeout causes the calling thread to release its monitor lock and enter the WAITING state. It will remain in this state until another thread calls `object.notify()` or `object.notifyAll()`.
Q1829easycode output
What does this code print?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Programming");
sb.insert(4, "-");
System.out.print(sb);
}
}
✅ Correct Answer: A) Prog-ramming
The `insert(offset, string)` method inserts the string at the specified offset. In 'Programming', 'P' is at index 0, so inserting at index 4 means after 'Prog'.
Q1830hardcode output
What is the output of this code?
java
import java.util.TreeSet;
import java.util.Comparator;
public class App {
static class Person implements Comparable<Person> {
String name; int age;
public Person(String name, int age) { this.name = name; this.age = age; }
@Override public int compareTo(Person other) { return this.name.compareTo(other.name); }
@Override public String toString() { return name + ":" + age; }
}
public static void main(String[] args) {
TreeSet<Person> people = new TreeSet<>(new Comparator<Person>() {
@Override public int compare(Person p1, Person p2) { return Integer.compare(p1.age, p2.age); }
});
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 30)); // Same age as Alice
System.out.println(people.size());
}
}
✅ Correct Answer: A) 2
When a TreeSet is constructed with a custom Comparator, it takes precedence over the natural ordering (compareTo method) of the elements. The Comparator here orders by 'age' only. Since 'Alice' (30) and 'Charlie' (30) have the same age, they are considered equal by the set's ordering, and only one is added.
Q1831hard
When `BufferedReader.skip(long n)` is called, how does it typically interact with the internal buffer of the `BufferedReader`?
✅ Correct Answer: B) `skip()` first attempts to consume characters from the internal buffer and then delegates any remaining `n` to the underlying stream's `skip()` method.
`BufferedReader.skip(n)` prioritizes skipping characters already present in its internal buffer. If `n` is greater than the buffered content, it then drains the buffer and calls the underlying `Reader`'s `skip()` method for the remaining characters.
Q1832easycode error
What error will occur when this code is executed?
java
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(-5);
sb.append("Data");
System.out.println(sb);
}
}
✅ Correct Answer: B) NegativeArraySizeException
Initializing a `StringBuffer` with a negative capacity value will cause a `NegativeArraySizeException` at runtime, as array sizes cannot be negative.
Q1833hard
Which of the following types is NOT permitted as the selector expression for a Java `switch` *statement* (prior to Java 12 `switch` expressions)?
✅ Correct Answer: B) java.lang.Long
The `switch` statement in Java supports `byte`, `short`, `char`, `int`, their wrapper types (`Byte`, `Short`, `Character`, `Integer`), `String` (since Java 7), and `Enum` types (since Java 5). `long`, `float`, `double`, and `boolean`, along with their wrapper types, are not permitted.
new String() creates a heap object. String literals go into the String Pool. intern() returns the canonical representation from the pool. s2 and s3 both refer to the same 'test' object in the pool.
Q1835mediumcode error
Which error will be encountered during the compilation of this Java code snippet?
java
public class MyWorker {
public void performWork() {
System.out.println("Worker performing work.");
}
}
public class Main {
public static void main(String[] args) {
MyWorker worker = new MyWorker();
Thread thread = new Thread(worker);
thread.start();
}
}
✅ Correct Answer: A) Compilation error: No suitable constructor found for Thread(MyWorker).
The `Thread` class constructors that accept an object as an argument specifically expect an object of type `Runnable`. Since `MyWorker` does not implement `Runnable`, there is no suitable constructor for `Thread(MyWorker)`, leading to a compilation error.
Q1836easycode error
Examine the following abstract class. What happens when you try to compile it?
java
abstract class Shape {
abstract void draw();
void draw() {
System.out.println("Drawing a generic shape.");
}
}
✅ Correct Answer: A) Compile-time error: Method 'draw()' is already defined in 'Shape'.
An abstract method declares a signature without an implementation, while a concrete method provides an implementation. Having both an abstract method and a concrete method with the exact same signature in the same class is illegal, as it means the method 'draw()' is defined twice (once as abstract, once as concrete), leading to a compile-time error.
Q1837hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("initial");
sb.ensureCapacity(20);
sb.append(" more text");
sb.trimToSize();
System.out.println(sb.capacity());
}
}
✅ Correct Answer: A) 17
Initially, capacity is 16 + 'initial'. `ensureCapacity(20)` ensures capacity is at least 20. `append(" more text")` makes the length 7 + 10 = 17. `trimToSize()` reduces the capacity to exactly match the current length, which is 17.
Q1838easycode error
What will be the output or error when running this code?
java
class Printer {
void printMessage() {
System.out.println("Hello from Printer!");
}
}
public class Main {
public static void main(String[] args) {
Printer p = null;
p.printMessage();
}
}
✅ Correct Answer: C) Runtime Error: NullPointerException
When a reference variable points to `null` and you attempt to call an instance method on it, a `NullPointerException` occurs at runtime.
Q1839hard
Which of the following statements correctly describes a characteristic of primitive type casting in Java?
✅ Correct Answer: D) An explicit cast from `float` to `int` truncates the decimal part, potentially leading to data loss.
Explicit casts for narrowing primitive conversions (like `float` to `int`) truncate the decimal part, discarding any fractional component and potentially leading to data loss. Implicit narrowing conversions are not allowed directly, and widening conversions are always safe and do not require a cast.
Q1840mediumcode output
What does this Java code print?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<>();
items.add("Pen");
items.add("Book");
System.out.println(items.contains("Book") + " " + items.contains("Pencil"));
}
}
✅ Correct Answer: A) true false
The `contains(Object)` method checks if the list contains the specified element. "Book" is present, so `items.contains("Book")` returns `true`. "Pencil" is not present, so `items.contains("Pencil")` returns `false`.