import java.util.function.Function;
public class LambdaTest {
public static void main(String[] args) {
Function<Integer, Integer> doubler = x -> x * 2;
System.out.println(doubler.apply(4));
}
}
✅ Correct Answer: A) 8
A `Function` lambda takes an input and produces an output. The `doubler` lambda multiplies its input by 2, so `apply(4)` returns 8.
Q3922hardcode output
Assume a file named 'data.txt' exists and contains the text "Hello World". What does this code print?
java
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
public class FileReaderSkip {
public static void main(String[] args) throws IOException {
// Assume 'data.txt' has content: "Hello World"
StringBuilder sb = new StringBuilder();
try (FileReader reader = new FileReader(new File("data.txt"))) {
reader.skip(5);
int c = reader.read(); // Read ' ' (space)
sb.append((char) c);
reader.skip(Long.MAX_VALUE); // Skip past EOF
c = reader.read(); // Should be -1
sb.append(c); // Appends -1 as string "-1"
}
System.out.println(sb.toString());
}
}
✅ Correct Answer: B) -1
The first `skip(5)` moves the reader past "Hello". The first `read()` then reads the space character. The second `skip(Long.MAX_VALUE)` moves the reader to the end of the file. Subsequent `read()` calls return -1, which is then appended as the string "-1".
Q3923medium
Why is calling the `close()` method on a `FileWriter` instance crucial after finishing writing operations?
✅ Correct Answer: B) To ensure all buffered data is flushed to the file and system resources are released.
`close()` flushes any data that might still be in internal buffers to the file and releases the operating system resources associated with the file handle. Failing to close can lead to data loss or resource leaks.
Q3924easy
Which of the following symbols is used as the 'arrow token' to separate parameters from the body of a lambda expression?
✅ Correct Answer: B) ->
The `->` symbol is the lambda operator, also known as the arrow token, which separates the lambda's parameters from its body.
Q3925easycode output
What does this Java code print?
java
public class StringPoolTest {
public static void main(String[] args) {
String s1 = "test";
String s2 = "test";
System.out.println(s1 == s2);
}
}
✅ Correct Answer: A) true
When String literals are used, Java's String pool ensures that if the content is identical, the same String object is reused. Since `s1` and `s2` refer to the same immutable literal in the pool, `==` returns true.
Q3926medium
`FileWriter` is a subclass of which abstract class in the `java.io` package, representing character output streams?
✅ Correct Answer: B) `Writer`
`FileWriter` extends `OutputStreamWriter`, which in turn extends the abstract `Writer` class, making `Writer` the fundamental abstract class for character-based output.
Q3927easy
When defining a lambda expression with a single parameter, under what condition can you omit the parentheses around the parameter?
✅ Correct Answer: C) Only when the parameter type is inferred and there is exactly one parameter.
Parentheses can be omitted for a single parameter if its type can be inferred by the compiler. If there are multiple parameters or the type is explicitly declared, parentheses are required.
Q3928hard
Consider the following Java code: `byte b = 10; b = b + 1;` Which statement about this code is true?
✅ Correct Answer: B) The code results in a compile-time error because `b + 1` evaluates to an `int`, which cannot be implicitly assigned back to a `byte`.
In Java, arithmetic operations on `byte` or `short` operands promote them to `int`. So `b + 1` evaluates to an `int`. An `int` cannot be implicitly assigned to a `byte` without an explicit cast, leading to a compile-time error. Compound assignment operators like `+=` include an implicit cast.
Q3929easycode error
What is the compile-time error in this Java class attempting to use a 'native' method?
java
class HardwareInterface {
public native void configurePort(int portNumber);
public void configurePort(int portNumber) {
System.out.println("Configuring port: " + portNumber);
}
}
✅ Correct Answer: A) Compile-time error: Method 'configurePort(int)' is already defined in 'HardwareInterface'.
The 'native' keyword signifies that the method's implementation is provided in another language (e.g., C/C++). However, it does not alter the method's signature for overloading rules. Defining both a 'native' method and a regular Java method with the exact same name and parameter list results in a compile-time error because the method 'configurePort(int)' is already defined.
Q3930easy
Can a Java class have multiple constructors?
✅ Correct Answer: B) Yes, through constructor overloading (different parameter lists).
A class can indeed have multiple constructors, as long as each has a unique parameter list; this concept is known as constructor overloading.
Q3931hardcode output
What is the output of this code?
java
public class IntegerObjectEqualityWhile {
public static void main(String[] args) {
Integer i = 0;
Integer limit = 150;
int count = 0;
while (i != limit) {
count++;
i = i + 1;
}
System.out.println("Final state: " + count + ", " + i.intValue());
}
}
✅ Correct Answer: A) Infinite Loop
For `Integer` values outside the cache range (-128 to 127), `Integer.valueOf(int)` creates new objects. `i = i + 1` involves autoboxing `i.intValue() + 1` into a new `Integer` object. Since `150` is outside the cache, `i` and `limit` will be distinct `Integer` objects with the same primitive value, so `i != limit` (comparing references) will always be true, leading to an infinite loop.
Q3932hard
Consider a scenario where a `FileReader` instance is created and then immediately closed. If a subsequent attempt is made to read data from this same `FileReader` instance, what is the expected behavior?
✅ Correct Answer: C) An `IOException` will be thrown, specifically indicating that the stream is closed.
Once a FileReader is closed, any subsequent attempts to perform read operations on that instance will result in an IOException, typically a 'Stream closed' message, as the underlying resource is no longer available for reading.
Q3933medium
In modern Java (Java 17 and later), what happens if the controlling expression of a `switch` statement or expression evaluates to `null`?
✅ Correct Answer: B) A `NullPointerException` will be thrown.
If the `switch` expression evaluates to `null`, a `NullPointerException` will be thrown. The `default` case does not handle `null` specifically unless an explicit `case null` label (Java 17+) is used for pattern matching.
Q3934medium
Which of the following is NOT a functional interface provided by Java's `java.util.function` package?
✅ Correct Answer: C) `Callable<V>`
`Callable<V>` is part of `java.util.concurrent` and represents a task that returns a result and may throw an exception. `Consumer`, `Predicate`, and `Function` are core functional interfaces introduced in Java 8 for common lambda expression patterns.
Q3935hardcode error
What does this code print?
java
import java.io.*;
import java.nio.charset.StandardCharsets;
public class EncodingErrorTest {
public static void main(String[] args) {
byte[] rawBytes = {(byte) 0xC3, (byte) 0x28}; // Invalid UTF-8 sequence
try (ByteArrayInputStream bis = new ByteArrayInputStream(rawBytes);
InputStreamReader isr = new InputStreamReader(bis, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
System.out.println(br.readLine()); // Attempt to read invalid UTF-8
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Error: Input length = 1
When `BufferedReader` reads through an `InputStreamReader` configured for `UTF-8` and encounters a byte sequence (0xC3 0x28) that is not a valid UTF-8 representation, it throws a `MalformedInputException` (a subtype of `IOException`) because the characters cannot be properly decoded.
Q3936easycode output
What will be printed when this Java code runs?
java
public class MyClass {
public static void main(String[] args) {
int value = 5;
String message = "";
switch (value) {
default: message = "Default Message"; break;
case 1: message = "Case 1"; break;
case 2: message = "Case 2"; break;
}
System.out.print(message);
}
}
✅ Correct Answer: C) Default Message
The 'default' case can be placed anywhere in a switch statement. Since 'value' (5) does not match 'case 1' or 'case 2', the 'default' case is executed. It sets 'message' to 'Default Message', and the 'break' statement prevents fall-through to subsequent cases.
Q3937hardcode error
What is the result of running this Java code?
java
import java.util.TreeMap;
public class TreeMapError1 {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "One");
map.put(null, "Null Value");
System.out.println(map.size());
}
}
✅ Correct Answer: B) A NullPointerException is thrown.
`TreeMap` does not permit null keys when using its natural ordering or if a custom comparator is not provided to handle nulls. Attempting to insert a null key will result in a `NullPointerException` during the comparison process.
Q3938hard
Consider the code:
java
Integer[][] matrix = new Integer[2][];
System.out.println(matrix[0]);
What will be printed to the console?
✅ Correct Answer: B) `null`
When `new Integer[2][]` is executed, the `matrix` array is created, capable of holding two `Integer[]` references. By default, these object references are initialized to `null`, thus printing `null`.
Q3939easycode output
What does this code print?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
ts.add(1);
ts.add(2);
System.out.println(ts.isEmpty());
ts.clear();
System.out.println(ts.isEmpty());
}
}
✅ Correct Answer: B) false
true
Initially, the TreeSet contains elements, so isEmpty() returns false. After calling clear(), all elements are removed, making the set empty, so isEmpty() then returns true.
Q3940easy
Which of the following is a common pre-defined functional interface found in the `java.util.function` package?
✅ Correct Answer: C) `java.util.function.Predicate`
`Predicate` is a widely used functional interface from the `java.util.function` package, representing an operation that takes one argument and returns a boolean result.