Return to site

[VV101] The Java 21 Newsletter

· java21,ocp

Stream reduce

Default and static methods

Duration dividedBy

StringBuilder constructors

Sequenced Collections or not?

ConcurrentHasMap constructors

SortedSet headSet

#vvauban #newsletter #java #java21

1️⃣ How would you answer this question:

What do the following print?

A) Java

B) null

C) Optional[Java]

D) Compilation fails

#PathToJava21 #java #certification

💡Solution

The correct answer is C) Optional[Java].

Explanation:

Stream.reduce() Without an Identity:

The reduce method is called without an identity value.

When this happens, the result is wrapped in an Optional.

This is done to handle the case where the stream is empty, in which case Optional.empty() is returned.

The method signature being used here is:

Optional reduce(BinaryOperator accumulator);

String::concat:

The String::concat method is passed as the accumulator.

It concatenates the elements of the stream in the order they are encountered.

The stream contains the elements "J", "a", "v", and "a", so they are concatenated to form "Java".

Output:

Since the result of reduce is wrapped in an Optional, the output is:

Optional[Java]

Key Observations:

If the stream were empty, the result would be Optional.empty().

If an identity value (e.g., "") had been provided, the output would be a plain string (Java).

Code Behavior Recap:

The program processes the stream and concatenates its elements, printing the result wrapped in an Optional.

 

 

 

2️⃣ How would you answer this question:

What do the following print?

A) default

B) static

C) nothing

D) Compilation fails

#PathToJava21 #java #certification

💡Solution

Compilation fails.

Why Does Compilation Fail?

The issue lies in the fact that static methods in interfaces cannot override instance methods, including default methods.

Breakdown of the Code:

Default Method in WithDefaultMethod:

The WithDefaultMethod interface defines a default method print(). A default method is an instance method with a default implementation.

Static Method in WithStaticMethod:

The WithStaticMethod interface extends WithDefaultMethod and declares a static method print().

However, Java does not allow a static method in an interface to have the same name and signature as an instance method (including default methods) in a parent interface.

This creates a conflict because the static method is not overriding the default method—it simply cannot coexist with it.

Compilation Error:

The Java compiler reports an error:

Static method 'print()' in 'WithStaticMethod' cannot override instance method 'print()' in 'WithDefaultMethod'.

Why Is This Forbidden?

Static methods in interfaces are associated with the interface itself, not its instances. They are not part of the instance method table.

Default methods, on the other hand, are instance methods.

Allowing both with the same name would create ambiguity in method resolution

 

 

 

3️⃣ How would you answer this question:

What do the following print?

A) PT0D

B) PT0H

C) PT6H

D) It throws an ArithmeticException

E) Compilation fails

#PathToJava21 #java #certification

💡Solution

PT6H. Let me clarify everything:

Explanation:

Duration.ofDays(2):

The Duration.ofDays(2) method creates a Duration object representing 2 days.

Internally, this is stored as 48 hours (2 days × 24 hours/day).

The dividedBy(int divisor) Method:

This method divides the duration by the provided divisor.

In this case:

48 hours ÷ 8 = 6 hours

48 hours ÷ 8 = 6 hours

Result:

The result is a new Duration object representing 6 hours.

This is printed in the ISO-8601 duration format: PT6H, where:

P indicates a period.

T separates the time component.

6H represents 6 hours.

Code Output:

The program successfully prints:

PT6H

 

 


4️⃣ How would you answer this question:

Could you tell me which StringBuilder variable doesn't compile?

A) stringBuilder1

B) stringBuilder2

C) stringBuilder3

D) stringBuilder4

E) None of them

#PathToJava21 #java #certification

💡 Solution

stringBuilder4.

Explanation:

stringBuilder1 = new StringBuilder();

This is valid.

Creates a StringBuilder with an initial capacity of 16 (default capacity).

stringBuilder2 = new StringBuilder(10);

This is valid.

Creates a StringBuilder with an initial capacity of 10.

stringBuilder3 = new StringBuilder("Java");

This is valid.

Creates a StringBuilder initialized with the content "Java" and a capacity of 4 + 16 = 20 (content length + default capacity).

stringBuilder4 = new StringBuilder(new char[]{'J', 'a', 'v', 'a'});

This is invalid and fails to compile.

The StringBuilder constructor does not accept a char[] as an argument.

It only accepts a String argument or an integer for capacity.

Compilation Error for stringBuilder4:

The compiler will report:

Error: no suitable constructor found for StringBuilder(char[])

Correct Code (if you want to initialize with a char[]):

You need to convert the char[] to a String:

var stringBuilder4 = new StringBuilder(new String(new char[]{'J', 'a', 'v', 'a'}));

This will compile and work correctly.


 

5️⃣ How would you answer this question:

What is printed?

A)

[Java, Scala, Kotlin]

[TypeScript, JavaScript]

B)

[Java, Scala, Kotlin]

[JavaScript, TypeScript]

C) We can't know

D) An exception is thrown

E) Compilation fails

#PathToJava21 #java #certification


💡 Solution

Compilation fails.

Java 21 introduced Sequenced collections.

Look at the schema of inheritance in comment.

You will understand that List gets the new API addFirst, removeLast, and reversed.

While Set does not.

So calling reversed on a Set causes compilation failure.

Line "js.reversed();" is incorrect.

🎬 Check this video: https://youtu.be/FeBPlcQc0EE




6️⃣ How would you answer this question:

How would you create a ConcurrentHashMap configured to allow a maximum of 10 concurrent writer threads and an initial capacity of 42?

Which of the following options meets this requirement?

A) concurrentHashMap1

B) concurrentHashMap2

C) concurrentHashMap3

D) concurrentHashMap4

E) None of them.

#PathToJava21 #java #certification

💡 Solution

According to the JavaDoc, the constructors are:

ConcurrentHashMap()

Creates a new, empty map with the default initial table size (16).

ConcurrentHashMap(int initialCapacity)

Creates a new, empty map with an initial table size accommodating the specified number of elements without the need to dynamically resize.

ConcurrentHashMap(int initialCapacity, float loadFactor)

Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity) and initial table density (loadFactor).

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity), initial table density (loadFactor), and number of concurrently updating threads (concurrencyLevel).

ConcurrentHashMap(Map m)

Creates a new map with the same mappings as the given map.

So the answer is: concurrentHashMap4


7️⃣ How would you answer this question:

Given:

What will be printed?

A) [Paris]

B) [Lyon, Lille, Toulouse]

C) [Lille, Lyon]

D) [Paris, Toulouse]

E) Compilation fails

#PathToJava21 #java #certification

💡 Solution

headSet

public SortedSet headSet(E toElement)

Description copied from interface: NavigableSet

Returns a view of the portion of this set whose elements are strictly less than toElement.

The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.

The returned set supports all optional set operations that this set supports.

The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.

Equivalent to headSet(toElement, false).

Specified by:

headSet in interface NavigableSet

Specified by:

headSet in interface SortedSet

Parameters:

toElement - high endpoint (exclusive) of the returned set

Returns:

a view of the portion of this set whose elements are strictly less than toElement

Throws:

ClassCastException - if toElement is not compatible with this set's comparator (or, if the set has no comparator, if toElement does not implement Comparable).

Implementations may, but are not required to, throw this exception if toElement cannot be compared to elements currently in the set.

NullPointerException - if toElement is null and this set uses natural ordering, or its comparator does not permit null elements

IllegalArgumentException - if this set itself has a restricted range, and toElement lies outside the bounds of the range

So the answer is: [Lille, Lyon]