Return to site

[VV114] The Java 21 Newsletter

· java21,java,ocp

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

1️⃣ How would you answer this question:

Given:

What is printed?

A) Anticonstitutionnellement

B) Hexakosioihexekontahexaphobie

C) 25

D) 29

E) An exception is thrown at runtime.

F) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Let's break down the code step by step.

1. Understanding BinaryOperator.maxBy

BinaryOperator longestFrenchWord = BinaryOperator.maxBy(Comparator.comparingInt(String::length));

BinaryOperator is a functional interface that takes two String arguments and returns one.

maxBy(Comparator.comparingInt(String::length)) creates a comparator that compares strings by their length.

The apply method of this BinaryOperator returns the longer of the two input strings.

2. Defining the Strings

String unconstitutionally = "Anticonstitutionnellement"; // 25 characters

String hexakosioihexekontahexaphobia = "Hexakosioihexekontahexaphobie"; // 29 characters

"Anticonstitutionnellement" has 25 characters.

"Hexakosioihexekontahexaphobie" has 29 characters.

3. Applying the BinaryOperator

System.out.println(longestFrenchWord.apply(unconstitutionally, hexakosioihexekontahexaphobia));

The comparator checks the length of both words.

"Hexakosioihexekontahexaphobie" is longer (29 characters), so it is returned.

4. What is printed?

The output is:

B) Hexakosioihexekontahexaphobie ✅

5. Verifying Other Options

A) "Anticonstitutionnellement" ❌ (Incorrect, since it's shorter)

C) 25 ❌ (Incorrect, length is not printed)

D) 29 ❌ (Incorrect, length is not printed)

E) An exception is thrown at runtime. ❌ (Incorrect, no exceptions occur)

F) Compilation fails. ❌ (Incorrect, code compiles successfully)

Final Answer:

✅ B) Hexakosioihexekontahexaphobie

(Working with Streams and Lambda expressions)

2️⃣ How would you answer this question:

Given:

What is printed?

A) coffee

B) tea

C) Optional[coffee]

D) Optional[tea]

E) An exception is thrown at runtime.

F) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

C) Optional[coffee]

Explanation:

The method or(Supplier> supplier) in Optional works as follows:

If the Optional on which it is called is non-empty, it returns that Optional.

If it is empty, it invokes the provided supplier and returns its result.

In the given code:

Optional.of("coffee") creates a non-empty Optional containing "coffee".

Optional.of("tea") creates a non-empty Optional containing "tea", but it is not used unless needed.

coffee.or(() -> tea) checks if coffee is present.

Since it is, it returns coffee without calling the supplier.

The output is Optional[coffee].

Thus, the correct answer is C) Optional[coffee].

Optional: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Optional.html

(Working with Streams and Lambda expressions)

3️⃣ How would you answer this question:

Given:

and given:

Which of the following statements is true?

A) getPerimeter compiles.

B) It fails to compile at line n1.

C) It fails to compile at line n2.

D) An exception is thrown at runtime when executing getPerimeter.

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

B) It fails to compile at line n1.

Explanation:

1. Understanding instanceof with Pattern Matching

The instanceof pattern matching allows variable declaration within the if statement:

if (shape instanceof Rectangle r) {

System.out.println(r.length()); // Valid here

}

The scope of the pattern variable (r in this case) is limited only within the block where instanceof is true.

2. Error at Line n1: if (shape instanceof Rectangle r || r.length() > 0)

The logical OR (||) operator short-circuits, meaning:

If shape instanceof Rectangle is false, the right-hand side (r.length() > 0) still gets evaluated.

But r is not defined unless shape instanceof Rectangle is true.

This results in a compilation error since r may be accessed when it has not been initialized.

3. Checking Line n2: else if (shape instanceof Circle c && c.length() > 0)

No issue here because:

The && operator ensures c is only used if shape instanceof Circle is true.

c is properly in scope before c.length() is accessed.

4. Conclusion

The compilation error occurs at line n1, not at line n2.

Since the code does not compile, runtime exceptions are irrelevant.

Thus, option B ("It fails to compile at line n1.") is the correct answer.

(Using Object-Oriented Concepts in Java)

4️⃣ How would you answer this question:

Given:

What is printed?

A) int

B) char

C) An exception is thrown at runtime.

D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Step-by-Step Analysis

1. char c = 65; → Char gets boxed into Character

char c = 65; // Equivalent to char c = 'A';

print(c);

char is a primitive type, but Java automatically boxes it when passing it to print(Object o).

So print(Character.valueOf('A')) is called.

2. Pattern Matching switch on Object

switch uses pattern matching, which was finalized in Java 21.

o is a Character object, so pattern matching checks:

Is o an Integer? ❌ (No, it's a Character).

Is o a Character? ✅ (Yes, o is Character.valueOf('A')).

Print "char" → ✅ Output: "char".

Final Answer:

✅ B) char

Pattern Matching for switch Expressions and Statements: https://docs.oracle.com/en/java/javase/21/language/pattern-matching-switch.html

(Using Object-Oriented Concepts in Java)

5️⃣ How would you answer this question:

Given:

What is printed?

A) [8, 9, 11]

B) [1, 3, 1]

C) An exception is thrown at runtime.

D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Let's analyze the code step by step and determine the correct output.

Step 1: Creating the Stream

We have a Stream containing the following French kings' names:

Step 2: Collecting into a Map

The collect operation groups the elements by their length (String::length) and counts how many times each length appears.

Using Collectors.groupingBy(String::length, Collectors.counting()), we get:

- 8 characters → "Louis IX" → count = 1

- 9 characters → "Francis I", "Louis XIV", "Louis XVI" → count = 3

- 11 characters → "Charlemagne" → count = 1

So, the resulting Map will be:

{8=1, 9=3, 11=1}

Step 3: Printing the Values

We print kingsMap.values(), which gives a collection of counts:

System.out.println(kingsMap.values());

This prints:

[1, 3, 1] (order may vary depending on the internal structure of the HashMap).

Correct Answer

✅ B) [1, 3, 1]

(Working with Streams and Lambda expressions)

6️⃣ How would you answer this question:

Given:

Which method causes a compilation error?

A) Everything is fine.

B) The abstract fuelConsumptionDuringNavigation method.

C) The static setDepartureLocation method.

D) The instance logCruise method.

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

B) The abstract fuelConsumptionDuringNavigation method.

Explanation:

Peniche is declared as a record.

- In Java, records are special classes introduced in Java 14 (preview) and finalized in Java 16.

- They are implicitly final, meaning they cannot be extended or be abstract.

- Since they cannot be abstract, they cannot contain abstract methods.

Why does fuelConsumptionDuringNavigation cause a compilation error?

- Declaring an abstract method within a record is illegal because a record is implicitly final.

- This violates Java's rules, which require abstract methods to be implemented in a subclass—but since records cannot be extended, this is not possible.

Other methods do not cause errors:

✅ setDepartureLocation(int latitude, int longitude)

This is a static method, which is perfectly fine in a record.

✅ logCruise()

This is a regular instance method, which is also valid in a record.

Conclusion

Since a record cannot have abstract methods, the abstract fuelConsumptionDuringNavigation method causes a compilation error.

Thus, the correct answer is:

B) The abstract fuelConsumptionDuringNavigation method. 🚀

(Using Object-Oriented Concepts in Java)