🛣️☕2️⃣1️⃣ Dear followers, let's prepare for Java 21 certification together!
1️⃣ How would you answer this question:
Given:
String colors = "red\n" +
"green\n" +
"blue\n";
Which text block can replace the above code?
A)
String colors = """
red \
green\
blue \
""";
B)
String colors = """
red \s
green\s
blue \s
""";
C)
String colors = """
red \t
green\t
blue \t
""";
D)
String name = """
red
green
blue
""";
E) None of the prepositions
#PathToJava21 #java #certification
💡 Solution
Question Analysis:
The code snippet:
String colors = "red\n" +
"green\n" +
"blue\n";
represents a multi-line string where each line ends with a newline character (\n).
Correct Answer:
D)
String colors = """
red
green
blue
""";
Explanation:
Text blocks preserve line breaks by default.
Option D results in:
red\n
green\n
blue\n
which matches the original String colors.
Why Other Options Are Incorrect:
A)
String colors = """
red \
green\
blue \
""";
The \ at the end of each line is a line continuation character, meaning no newline characters (\n) will be included between the lines.
This produces:
"red greenblue "
It does not match the original string because it lacks newlines.
B)
String colors = """
red \s
green\s
blue \s
""";
The \s is an escape sequence for a space character.
Adding it at the end of each line appends a space character to each line before the newline:
"red \n"
"green \n"
"blue \n"
This does not match the original string because of the trailing spaces.
C)
String colors = """
red \t
green\t
blue \t
""";
The \t is an escape sequence for a tab character.
Adding it at the end of each line appends a tab before the newline:
"red \t\n"
"green\t\n"
"blue \t\n"
This does not match the original string because of the additional tab characters.
E)
"None of the prepositions."
This is incorrect because D is a valid replacement.
Summary:
Correct Answer: D
Key Points:
Text blocks naturally preserve newlines, making D match the original string.
Other options modify the output by adding or removing characters, making them invalid.
The task is to find a text block that creates an identical result.
Programmer's Guide to Text Blocks: https://docs.oracle.com/en/java/javase/15/text-blocks/index.html
(Handling Date, Time, Text, Numeric and Boolean Values)
2️⃣ How would you answer this question:
Given:
What is printed?
A) integer
B) long
C) string
D) nothing
E) It throws an exception at runtime.
F) Compilation fails.
#PathToJava21 #java #certification
💡 Solution
Analysis:
Code Explanation:
The code tries to use pattern matching in a switch statement with primitive types (int and long), which is not allowed in Java.
Pattern matching for switch requires the use of reference types (e.g., Integer, Long, String).
Specifically, the case case int i -> "integer"; causes a compilation error, as the int type is primitive and cannot be used for pattern matching.
Why Compilation Fails:
Java's switch pattern matching operates on objects.
While myVar is declared as Object, its value is 0, which is an int.
The compiler does not allow primitive types in pattern matching.
Correct Usage:
If the goal is to handle int values, you must use the wrapper type Integer instead of int.
A corrected version of the code would look like this:
This code compiles successfully and outputs "integer".
Answer: The provided code does not compile due to the invalid use of a primitive type (int) in the switch pattern matching.
Correct Answer: F) Compilation fails.
(Controlling Program Flow)
3️⃣ How would you answer this question:
Given:
Which compiles?
A)
B)
C)
D)
E)
#PathToJava21 #java #certification
💡 Solution
Let's analyze each option:
Option A:
Does not compile.
frenchAuthors is declared as List, but the map authorsMap expects values of type ArrayList.
Even though frenchAuthors is an instance of ArrayList, its declared type is List.
Reason: Invariance of generics. List cannot be treated as ArrayList.
Option B:
Does not compile.
The wildcard ? extends List makes authorsMap2 a read-only map for values because the compiler cannot guarantee what specific subtype of List is allowed.
Reason: You cannot add elements to a collection with ? extends wildcard due to type safety concerns.
Option C:
Compiles and runs.
var infers the raw type HashMap.
While this works, it is not type-safe because it allows inserting any type of key or value into the map.
Reason: No generic type constraints are enforced due to raw type inference.
Option D:
Does not compile.
While ArrayList is a subtype of List, HashMap> is not a subtype of Map> due to invariance in Java generics.
Reason: Generic types are invariant, so the declared types of the HashMap and Map must exactly match.
Option E:
Compiles and runs.
The map is explicitly declared to accept List as values, and frenchAuthors is of type List.
The types match, so this is type-safe.
Reason: Both the map and the inserted value have the same generic type.
Summary of Validity
Option Compiles? Reason
A ❌ frenchAuthors is List, but the map expects ArrayList.
B ❌ Cannot put into ? extends List due to wildcard restrictions.
C ✅ var infers the raw type HashMap, allowing insertion without type checking.
D ❌ HashMap> cannot be assigned to Map> due to invariance.
E ✅ The map is explicitly defined to accept List, matching the type of frenchAuthors.
Best Practice:
Option E is the most type-safe and correct choice.
Avoid Option C because it sacrifices type safety by relying on raw types.
More Fun with Wildcards: https://docs.oracle.com/javase/tutorial/extra/generics/morefun.html
(Using Object-Oriented Concepts in Java)
4️⃣ How would you answer this question:
Given:
What is printed?
A) Numbers from 1 to 25 sequentially
B) Numbers from 1 to 25 randomly
C) Numbers from 1 to 1945 randomly
D) An exception is thrown at runtime
E) Compilation fails
#PathToJava21 #java #certification
💡 Solution
The correct answer is:
B) Numbers from 1 to 25 randomly
Explanation:
LongStream.range(1, 1945):
Generates a stream of long values from 1 (inclusive) to 1945 (exclusive).
The .boxed() method converts each primitive long value to a Long object.
The .toList() method collects all these Long objects into a List named cannesFestivalfeatureFilms.
Virtual Thread Executor:
Executors.newVirtualThreadPerTaskExecutor() creates an ExecutorService that uses virtual threads (a lightweight concurrency model introduced in Java).
The virtual thread executor schedules tasks asynchronously.
Processing the Stream:
The stream is limited to the first 25 elements (.limit(25)).
Each element is submitted to the virtual thread executor as a task (executor.submit(...)).
The System.out.println(film) statement is executed within the submitted task.
Order of Execution:
The forEach method processes the stream sequentially, but since the tasks are submitted to the executor and executed asynchronously, the order of execution is not guaranteed.
This results in the numbers being printed in a random order, depending on the scheduling and execution of the virtual threads.
No Compilation Errors or Exceptions:
The code is syntactically correct and uses valid APIs.
No runtime exception is thrown unless there's a specific issue with the environment (e.g., JVM configuration or resources).
Why the Other Options Are Incorrect:
A) Numbers from 1 to 25 sequentially: Incorrect, as the virtual thread executor introduces asynchronicity.
C) Numbers from 1 to 1945 randomly: Incorrect, as the .limit(25) method restricts the stream to the first 25 elements.
D) An exception is thrown at runtime: Incorrect, as there are no conditions in the code that cause an exception.
E) Compilation fails: Incorrect, as the code is valid and compiles without issues.
Virtual Threads: https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html
(Managing Concurrent Code Execution)
5️⃣ How would you answer this question:
Given:
A) 0
B) 1
C) 2
D) It throws an exception at runtime.
E) Compilation fails.
#PathToJava21 #java #certification
💡 Solution
To answer the question, let's analyze the code and evaluate its behavior step by step.
Code Analysis
Classes and Interface:
- Addition class:
Contains an instance variable foo initialized to 1.
- Special interface:
Contains a constant bar with value 1.
Note: Interface variables are public, static, and final by default. So, bar is a constant.
- SpecialAddition class:
Extends Addition and implements Special.
Contains a method add():
return --foo + bar--;
--foo: Decrements the foo instance variable and returns its new value.
bar--: Tries to decrement bar, but bar is a final variable, so modifying it is not allowed.
Key Observations
bar-- Causes Compilation Failure:
bar is declared as final in the Special interface (since all interface variables are final).
Attempting to modify a final variable results in a compilation error.
Correct Answer:
E) Compilation fails.
Why the Other Options Are Incorrect
A) 0, B) 1, C) 2:
These options assume the code compiles and executes successfully, which is not the case due to the bar-- error.
D) It throws an exception at runtime:
The code does not reach runtime due to the compilation failure.
Conclusion
The attempt to modify bar, a final variable, causes a compilation error.
Correct answer: E) Compilation fails.
[Java Language Specification] Field (Constant) Declarations:https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.3
Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.
(Using Object-Oriented Concepts in Java)
6️⃣ How would you answer this question:
Which of the following does not exist?
A) BooleanSupplier
B) DoubleSupplier
C) LongSupplier
D) Supplier
E) BiSupplier
F) They all exist
#PathToJava21 #java #certification
💡 Solution
The correct answer is:
E) BiSupplier
Explanation:
The Supplier functional interface is part of the java.util.function package in Java and represents a supplier of results.
Here are the valid supplier interfaces:
BooleanSupplier: Exists, and it supplies a boolean result.
DoubleSupplier: Exists, and it supplies a double result.
LongSupplier: Exists, and it supplies a long result.
Supplier: Exists, and it supplies a result of a generic type T.
However, there is no such thing as a BiSupplier in Java.
The supplier functional interfaces in Java only deal with supplying a single value, and
the concept of two inputs (as in Bi* interfaces) is typically associated with BiFunction or similar functional interfaces.
Package java.util.function: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/function/package-summary.html
(Working with Streams and Lambda expressions)