Return to site

[VV109] The Java 21 Newsletter

February 22, 2025

🛣️☕2️⃣1️⃣ Dear followers, let's prepare for Java 21 certification together!

1️⃣ How would you answer this question:

Given:

What is printed?

  • A) 2.5
  • B) 2.0
  • C) 2
  • D) An exception is thrown at runtime.
  • E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Step-by-step Analysis:

- Creating a Stream:

Stream integers = Stream.of(1, 2, 3, 4);

This creates a Stream containing the values {1, 2, 3, 4}.

- Using Collectors.averagingInt:

double average = integers.collect(Collectors.averagingInt(i -> i));

The averagingInt collector takes an int function and computes the arithmetic mean of the elements.

The sum of {1, 2, 3, 4} is 1 + 2 + 3 + 4 = 10.

The count of elements is 4.

The average is calculated as 10 / 4 = 2.5, which is stored in average as a double.

- Printing the result:

System.out.println(average);

This prints 2.5.

Answer:

✅ A) 2.5

(Working with Streams and Lambda expressions)

2️⃣ How would you answer this question:

Given:

What is printed?

A) 0

B) Infinity

C) An exception is thrown at runtime.

D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Let's analyze:

- Step 1: Checking for Compilation Errors

The declaration of pi contains an underscore (_) in 3._141592653f.

Underscores are allowed in numeric literals in Java, but they cannot be placed at the beginning or end of a number.

The correct way would be:

float pi = 3.141592653f;

Because of this misplaced underscore, compilation will fail.

- Step 2: Evaluating Division by Zero (if code compiled)

If the underscore were corrected, the division pi / zero would be evaluated as:

In Java, floating-point division by zero does not throw an exception.

Instead:

Positive float/zero (positive / 0.0) results in Infinity.

Negative float/zero (negative / 0.0) results in -Infinity.

Zero divided by zero (0.0 / 0.0) results in NaN.

However, since zero is an int, Java will promote it to a float automatically, making it 0.0f.

Thus, pi / zero would be Infinity if the code were valid.

- Step 3: Final Answer

Since the incorrect underscore causes a compilation error, the correct answer is:

E) Compilation fails.

Using Underscore Characters in Numeric Literals: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

(Working with Streams and Lambda expressions)

3️⃣ How would you answer this question:

Given:

What is printed?

A) 2.5

B) 4.5

C) 4.25

D) 2.25

E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Let's analyze the given Java code step by step.

- Step 1: Understanding compose

The compose method is defined in Function as:

default Function compose(Function before)

It takes a function before and applies it before the current function.

The before function returns a value that is then passed to the original function.

Here, floatify is:

Function floatify = Float::parseFloat;

floatify.compose((String str) -> str + ".25") first applies (String str) -> str + ".25", which appends ".25" to the input string.

Then, it applies Float::parseFloat to convert the result to a Float.

- Step 2: Understanding andThen

The andThen method is defined as:

default Function andThen(Function after)

It applies the original function and then applies the after function.

The after function takes the result of the original function and processes it.

Here, andThen( num -> num * 2 ) will take the Float result from floatify and multiply it by 2.

- Step 3: Evaluating apply("2")

compose first executes (String str) -> str + ".25":

Input: "2"

Output: "2.25"

Then, floatify (which is Float::parseFloat) parses "2.25":

Output: 2.25f

andThen executes num -> num * 2:

Input: 2.25f

Output: 4.5f

- Step 4: Expected Output

The final result is 4.5f, so the output printed is:

4.5

Correct Answer:

B) 4.5

default Function compose(Function before)

Returns a composed function that first applies the before function to its input, and then applies this function to the result.

(Working with Streams and Lambda expressions)

4️⃣ How would you answer this question:

Given:

What is printed?

A) [13000]

B) [13000, 69000]

C) Nothing

D) An exception is thrown.

E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The correct answer is E) Compilation fails.

Here's why:

The south predicate is defined as Predicate south = (zipcode) -> southZipCodes.contains(zipcode);,

and it refers to the variable southZipCodes.

In Java, variables used in lambda expressions must be final or effectively final, meaning their value cannot change after they are assigned.

However, in the code, southZipCodes is reassigned after the lambda expression is defined (southZipCodes = List.of(06000, 13000, 31000, 33000, 69000);),

which breaks this rule.

Since southZipCodes is no longer effectively final after this reassignment, the code will fail to compile.

If southZipCodes had been declared as final or its value remained unchanged, the code would have worked as expecte

Accessing Local Variables of the Enclosing Scope

Like local and anonymous classes, a lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final.

(Working with Streams and Lambda expressions)

5️⃣ How would you answer this question:

Which of the following statements about try-with-resources are true? Choose 3.

A) The close methods of resources are called in the opposite order of their creation.

B) Any catch or finally block is run after the resources declared have been closed.

C) Any object that implements java.lang.AutoCloseable can be used as a resource.

D) The close method of the AutoCloseable interface throws exceptions of type IOException.

#PathToJava21 #java #certification

💡 Solution

The correct answers are:

✅ A) The close methods of resources are called in the opposite order of their creation.

✅ B) Any catch or finally block is run after the resources declared have been closed.

✅ C) Any object that implements java.lang.AutoCloseable can be used as a resource.

Explanation:

A) ✅ True → In a try-with-resources block, resources are closed in the reverse order of their creation, ensuring proper cleanup.

B) ✅ True → After closing the resources, any catch or finally block is executed, following normal exception handling rules.

C) ✅ True → The try-with-resources statement works with any class that implements java.lang.AutoCloseable, which includes java.io.Closeable as well.

D) ❌ False → The close() method of AutoCloseable can throw any exception (not just IOException).

In contrast, Closeable (a subinterface) restricts exceptions to IOException.

(Handling Exceptions)

6️⃣ How would you answer this question:

Given:

Does this code compile?

A) It compiles successfully.

B) Compilation error at line n1.

C) Compilation error at line n2.

D) Compilation error at line n3.

E) Compilation error at line n4.

F) Compilation fails due to multiple compilation errors.

#PathToJava21 #java #certification

💡 Solution

The correct answer is E) Compilation error at line n4.

Explanation:

* Line n1 (getLocalDateTime())

- This method is declared but not implemented. However, this is allowed because TimeClient is an interface. Interfaces can have abstract methods that must be implemented by concrete classes.

- ✅ No compilation error.

* Line n2 (static getZoneId method)

- This is a static method in an interface, which has been allowed since Java 8. It has a valid implementation.

- ✅ No compilation error.

* Line n3 (default getZonedDateTime method)

- This is a default method, which is allowed in interfaces since Java 8. It calls the abstract method getLocalDateTime(), which concrete classes must implement.

- ✅ No compilation error.

* Line n4 (default equals method)

- Problem: The equals method in Object is already defined, and Java does not allow interfaces to override Object methods with default implementations. Only abstract declarations of equals, hashCode, or toString are permitted in interfaces.

- ❌ Compilation error at n4 due to this rule.

* Conclusion:

The code fails to compile due to the equals method at n4, making E) Compilation error at line n4 the correct answer.

(Using Object-Oriented Concepts in Java)