Return to site

[VV110] 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) North,

B) Seine,

C) Seine, Corsica

D) An exception is thrown at runtime.

E) Compilation fails.

#PathToJava21 #java #certification

🔎 More: https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

💡 Solution

Step 1: Understanding the Switch Execution

1. Variable Type:

- var department = 31; → Java infers it as an int.

- The switch statement works with int.

2. Case Matching:

- 31 is not explicitly listed in any case.

- Since no case matches 31, execution jumps to default (if present).

- There is a default case, so execution starts from default:.

3. Execution Flow (No break Statements!):

- default: case executes and falls through.

- case 69, 75: is next, so "Seine, " is printed.

4. Next, case 'a' | 'b':

- 'a' | 'b' results in 99 (ASCII value of 'c').

- Even though department != 99, execution is already in the flow due to fall-through.

- "Corsica" is printed.

Step 2: What Gets Printed?

- Execution starts at default → Falls through.

- Prints "Seine, ".

- Falls through to case 99 (from 'a' | 'b') → Prints "Corsica".

Final Output: Seine, Corsica

(Using Object-Oriented Concepts in Java)

2️⃣ How would you answer this question:

Which of the following can be used to create an ExecutorService? Choose 3.

A) Executors.newVirtualThreadPerTaskExecutor();

B) Executors.newFixedThreadPool(10);

C) new ExecutorService();

D) Executors.getFixedThreadPool(10);

E) Executors.createSingleThreadExecutor();

F) Executors.newSingleThreadExecutor();

#PathToJava21 #java #certification

💡 Solution

The correct answers are:

✅ A) Executors.newVirtualThreadPerTaskExecutor() → This method creates an ExecutorService that assigns each task to a new virtual thread, introduced in Java 21.

✅ B) Executors.newFixedThreadPool(10) → This method creates a fixed-size thread pool with 10 threads and returns an ExecutorService.

✅ F) Executors.newSingleThreadExecutor() → This method creates an ExecutorService with a single worker thread.

Explanation for Incorrect Options:

❌ C) new ExecutorService(); → ExecutorService is an interface, and interfaces cannot be instantiated directly.

❌ D) Executors.getFixedThreadPool(10); → This method does not exist in the Executors class.

❌ E) Executors.createSingleThreadExecutor(); → This method does not exist in the Executors class.

(Managing Concurrent Code Execution)

3️⃣ How would you answer this question:

Given:

Which code statement will NOT print '[Eiffel Tower 🗼, Croissant 🥐, Paris 🇫🇷, Wine 🍷, Château 🏰, Beret 🎩, Fromage 🧀, Riviera 🌊, Versailles 👑]'?

A) deque.remove();

B) deque.remove("Baguette 🥖");

C) deque.removeAll( List.of( "Baguette 🥖" ) );

D) deque.removeFirst();

E) deque.removeFirstOccurrence("Baguette 🥖");

F) deque.removeIf(item->item.equals("Baguette 🥖"));

G) deque.removeLast();

H) deque.removeLastOccurrence("Baguette 🥖");

I) None of the suggestions

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

G) deque.removeLast();

Explanation:

The given deque is an ArrayDeque, which follows FIFO (First In, First Out) behavior when using standard remove() or removeFirst() methods.

The expected output (after removing "Baguette 🥖") is:

[Eiffel Tower 🗼, Croissant 🥐, Paris 🇫🇷, Wine 🍷, Château 🏰, Beret 🎩, Fromage 🧀, Riviera 🌊, Versailles 👑]

Let's analyze each option:

✅ A) deque.remove();

remove() in ArrayDeque removes the head (first element).

Removes "Baguette 🥖".

Output remains as expected.

✅ B) deque.remove("Baguette 🥖");

Directly removes "Baguette 🥖".

Output remains as expected.

✅ C) deque.removeAll(List.of("Baguette 🥖"));

Removes "Baguette 🥖" if present.

Output remains as expected.

✅ D) deque.removeFirst();

Removes the first element, which is "Baguette 🥖".

Output remains as expected.

✅ E) deque.removeFirstOccurrence("Baguette 🥖"); (Incorrect Syntax)

It removes "Baguette 🥖".

Output remains as expected.

✅ F) deque.removeIf(item -> item.equals("Baguette 🥖"));

Removes "Baguette 🥖".

Output remains as expected.

❌ G) deque.removeLast(); (Wrong choice)

Removes the last element, which is "Versailles 👑", not "Baguette 🥖".

This changes the output, making it incorrect.

✅ H) deque.removeLastOccurrence("Baguette 🥖");

"Baguette 🥖" appears only once, so this works the same as remove("Baguette 🥖").

Output remains as expected.

✅ I) None of the suggestions (Incorrect)

Since G changes the output, this option is incorrect.

Final Answer:

G) deque.removeLast();

(Working with Arrays and Collections)

4️⃣ How would you answer this question:

Given:

What is printed?

A) Character

B) String

C) Long

D) An exception is thrown at runtime.

E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The given code attempts to use pattern matching in a switch statement, a feature introduced as a preview in Java 17 and standardized in Java 21.

However, it lacks break statements, which leads to an "Illegal fall-through to a pattern" compilation error.

Key Issues:

1. Pattern Matching in switch Requires No Fall-Through:

- In traditional switch statements, fall-through is allowed unless explicitly stopped with break.

- Pattern matching switch does not allow fall-through because each case is based on a distinct type, making fall-through meaningless.

2. Missing break Statements:

- Since there are no break statements, the compiler prevents fall-through between cases, leading to a compilation error.

How to Fix the Code

✅ Using Explicit break Statements (For Java 17+)

✅ Using Arrow Syntax (For Java 21+)

Java 21 allows the arrow (->) syntax, which eliminates fall-through and simplifies the switch statement:

Correct Answer:

E) Compilation fails.

💡 Takeaway:

In pattern-matching switch, fall-through is not allowed.

Use explicit break statements in Java 17+ or use the arrow (->) syntax in Java 21+ to avoid compilation errors.

Switch expression: https://docs.oracle.com/en/java/javase/21/language/switch-expressions-and-statements.html

(Using Object-Oriented Concepts in Java)

5️⃣ How would you answer this question:

Given:

Which statements are correct?

A) in line n1 it is a java.lang.Runnable implementation

B) in line n2 it is a java.util.concurrent.Callable implementation

C) in line n1 it is a java.util.concurrent.Callable implementation

D) in line n2 it is a java.lang.Runnable implementation

E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

* Step 1: Understanding submit Method Overloads

The ExecutorService interface provides two overloaded submit methods:

- Future submit(Runnable task);

Accepts a Runnable and returns a Future.

The Runnable interface has a single method:

void run();

Since Runnable.run() does not return any value, the returned Future will hold null.

- Future submit(Callable task);

Accepts a Callable and returns a Future.

The Callable interface has a single method:

T call() throws Exception;

This method returns a value, which can be retrieved from the returned Future.

* Step 2: Analyzing Line n1

service.submit(() -> {}); // n1

() -> {} is a lambda with an empty body.

The return type is void, which matches Runnable.run().

Since it matches Runnable, submit(Runnable task) is called.

Therefore, it is a Runnable implementation.

Thus, option A is correct:

✅ A) In line n1 it is a java.lang.Runnable implementation

* Step 3: Analyzing Line n2

service.submit(() -> 100); // n2

() -> 100 is a lambda that returns an int (which is auto-boxed to Integer).

Since it returns a value, it does not match Runnable.run() (which must return void).

Instead, it matches Callable.call() because call() can return a value.

This means that it is a Callable implementation.

Thus, option B is correct:

✅ B) In line n2 it is a java.lang.Callable implementation

(Managing Concurrent Code Execution)

6️⃣ How would you answer this question:

Given:

What is printed?

A) 2025-04-12

B) 2025-05-12

C) 2025-05-13

D) An exception is thrown at runtime.

E) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

Let's analyze the given code:

var year = Year.now();

var jConDate = year.atMonthDay(MonthDay.of(5, 13));

System.out.println(jConDate);

Step-by-step Analysis:

Year.now() retrieves the current year as a Year instance.

Since today is February 22, 2025, year will hold 2025.

MonthDay.of(5, 13) creates a MonthDay instance representing May 13th.

year.atMonthDay(MonthDay.of(5, 13)) converts the MonthDay into a LocalDate by combining it with year, resulting in 2025-05-13.

System.out.println(jConDate); will print this LocalDate.

Correct Answer:

✅ C) 2025-05-13

(Handling Date, Time, Text, Numeric and Boolean Values )