Return to site

[VV103] 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) [ ,hello,h i]
  • B) [,hello,h i]
  • C) [,hello,hi]
  • D) [ , hello ,hi ]

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

B) [,hello,h i]

Explanation:

Let's reevaluate the problem, knowing that strip() removes all leading and trailing whitespace.

Code Analysis:

First String: s = " "

s.strip() removes all leading and trailing spaces.

The resulting string is an empty string "".

The output is [.

Second String: s = " hello "

s.strip() removes all leading and trailing spaces.

The resulting string is "hello".

The output becomes [,hello.

Third String: s = "h i "

s.strip() removes only the trailing spaces, while the space between h and i remains.

The resulting string is "h i".

The output becomes [,hello,h i].

Final Answer:

B) [,hello,h i]

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

2️⃣ How would you answer this question:

Given:

What is printed?

  • A) truetruefalse
  • B) truetruetrue
  • C) truefalsetrue
  • D) falsetruetrue
  • E) Compilation fails

#PathToJava21 #java #certification

💡 Solution

To answer this question, let's analyze the code step by step.

Code Breakdown:

1 == 1 evaluates to true.

2 < 1 evaluates to false.

Boolean.logicalAnd(true, false) returns false because the logical AND operation returns true only if both operands are true.

The output is false.

1 == 1 evaluates to true.

2 < 1 evaluates to false.

Boolean.logicalOr(true, false) returns true because the logical OR operation returns true if at least one operand is true.

The output is true.

1 == 1 evaluates to true.

2 < 1 evaluates to false.

Boolean.logicalXor(true, false) returns true because the logical XOR operation returns true if exactly one operand is true.

The output is true.

Combined Output:

The output is: falsetruetrue

Final Answer:

D) falsetruetrue

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

3️⃣ How would you answer this question:

Given:

Which statement is correct?

  • A) It compiles
  • B) It does not compile
  • C) It throws an exception at runtime

#PathToJava21 #java #certification

💡 Solution

The correct answer is:

B) It does not compile

Explanation:

The problem lies in the cyclic constructor calls. Here's why:

Constructor Chaining:

In the ThisCalls class, the default constructor (public ThisCalls()) calls the parameterized constructor (public ThisCalls(boolean flag)) using this(true).

The parameterized constructor (public ThisCalls(boolean flag)) again calls the default constructor (this()).

Cyclic Dependency:

The default constructor and the parameterized constructor depend on each other in a cyclic manner:

ThisCalls() calls ThisCalls(boolean flag).

ThisCalls(boolean flag) calls ThisCalls().

This creates an infinite loop during constructor invocation, which the compiler detects as an error.

Compilation Error:

Java does not allow cyclic constructor calls. The compiler will produce an error like:

recursive constructor invocation

Final Answer:

B) It does not compile

(Using Object-Oriented Concepts in Java)


4️⃣ How would you answer this question:

Given:

Which arrays compile? (Select 2)

  • A) array1
  • B) array2
  • C) array3
  • D) array4
  • E) array5

#PathToJava21 #java #certification

💡 Solution

Correct Answers:

A) array1

E) array5

Let's analyze each array declaration to determine which ones will compile:

A) array1

var array1 = new String[]{ "foo", "bar", "buz" };

This syntax is correct.

Using new String[]{ ... } explicitly initializes a string array, and var allows the type to be inferred.

Compiles successfully.

B) array2

var array2[] = { "foo", "bar", "buz" };

This syntax is incorrect.

The var keyword cannot be used with array brackets ([]) as part of the variable name.

Does not compile.

C) array3

var array3 = new String[3] { "foo", "bar", "buz" };

This syntax is incorrect.

When specifying the size of an array (new String[3]), you cannot initialize its elements in the same statement.

Does not compile.

D) array4

var array4 = { "foo", "bar", "buz" };

This syntax is incorrect.

For type inference with var, the array must be explicitly initialized with new String[]{ ... }. Without the new String[], the compiler cannot infer the type.

Does not compile.

E) array5

String array5[] = new String[]{ "foo", "bar", "buz" };

This syntax is correct.

The new String[]{ ... } explicitly initializes the array, and the variable is declared as a String array.

Compiles successfully.

(Working with Arrays and Collections)

5️⃣ How would you answer this question:

Given:

and

What is printed?

  • A) Peugeot
  • B) Peugeot 807
  • C) An exception is thrown at runtime.
  • D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The correct answer is: D) Compilation fails.

Explanation:

Access Modifier - protected:

The brand field in the Car class is declared as protected. This means:

The brand field can be accessed by the same package classes (vehicule.parent) and subclasses of Car in different packages.

The issue in the MiniVan class:

The code tries to create an instance of Car using Car car = new Car(); in the MiniVan class, which is valid.

However, car.brand = "Peugeot 807"; causes a compilation error because:

brand is protected, so it is not directly accessible via an instance of Car unless the code is in the same package as Car.

Even though MiniVan is a subclass of Car, protected members are accessible only through inheritance and not through an instance of the parent class (like car.brand here).

Correct Usage:

If you want to access the brand field in MiniVan, you can do so via inheritance. For example:

The above code will compile and print Peugeot 807.

Summary:

In the original code, the compilation fails because a protected member cannot be accessed through an instance of the superclass from a different package.

(Using Object-Oriented Concepts in Java)

6️⃣ How would you answer this question:

Given:

What is printed?

  • A) Sum: 22.0, Max: 8.5, Avg: 5.5
  • B) Sum: 22.0, Max: 8.5, Avg: 5.0
  • C) An exception is thrown at runtime.
  • D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The correct answer is: A) Sum: 22.0, Max: 8.5, Avg: 5.5

Explanation:

Understanding DoubleSummaryStatistics methods:

  • accept(double value) adds the given value to the statistics.
  • combine(DoubleSummaryStatistics other) merges the statistics from the other instance into the current instance.
  • getSum() returns the total sum of all accepted values.
  • getMax() returns the maximum value among all accepted values.
  • getAverage() returns the arithmetic mean of all accepted values.

Step-by-step execution:

  • stats1:

- Accepts 4.5 → Sum: 4.5, Max: 4.5.

- Accepts 6.0 → Sum: 10.5, Max: 6.0.

  • stats2:

- Accepts 3.0 → Sum: 3.0, Max: 3.0.

- Accepts 8.5 → Sum: 11.5, Max: 8.5.

  • stats1.combine(stats2):

Combines stats2 into stats1:

- New Sum: 10.5 + 11.5 = 22.0.

- New Max: max(6.0, 8.5) = 8.5.

- Average: 22.0 / 4 = 5.5 (total of 4 values: 4.5, 6.0, 3.0, 8.5).

Output:

Sum: 22.0, Max: 8.5, Avg: 5.5.

Why other options are incorrect:

  • B) Avg is incorrectly calculated as 5.0. This option misunderstands the arithmetic mean.
  • C) An exception is not thrown because combine() and other operations are valid.
  • D) Compilation does not fail because the code is syntactically correct.

Thus, A) Sum: 22.0, Max: 8.5, Avg: 5.5 is the correct answer.

(Working with Streams and Lambda expressions)

7️⃣ How would you answer this question:

Given:

What is printed?

  • A) bread:Baguette, dish:Frog legs, cheese.
  • B) bread:Baguette, dish:Frog legs, no cheese.
  • C) bread:bread, dish:dish, cheese.
  • D) Compilation fails.

#PathToJava21 #java #certification

💡 Solution

The correct answer is: bread:Baguette, dish:Frog legs, no cheese.

Explanation:

Code Execution Details:

- optionalName:

Optional.ofNullable(null) creates an empty Optional because the input is null.

- orElse("Baguette"):

The orElse method always returns the provided value if the Optional is empty.

Output: bread:Baguette.

- orElseGet(() -> "Frog legs"):

The orElseGet method lazily evaluates the supplier only when the Optional is empty.

Output: dish:Frog legs.

- orElseThrow(() -> new Exception()):

The orElseThrow method throws an exception if the Optional is empty.

Since the Optional is empty, an exception is thrown, and the catch block is executed, printing no cheese.

Final Output:

bread:Baguette, dish:Frog legs, no cheese.

Why Other Options Are Incorrect:

- bread:Baguette, dish:Frog legs, cheese. Incorrect because the exception prevents "cheese" from being printed.

- bread:bread, dish:dish, cheese. Incorrect because "bread" and "dish" do not match the actual variable names or printed values.

- Compilation fails.: Incorrect because the code compiles successfully without any syntax errors.

Key Takeaway:

- orElse provides a default value directly.

- orElseGet evaluates a supplier lazily.

- orElseThrow throws an exception if the Optional is empty.

(Working with Streams and Lambda expressions)