[VV111] The Java 21 Newsletter
[VV111] The Java 21 Newsletter

[VV111] The Java 21 Newsletter

????2??1?? Dear followers, let's prepare for Java 21 certification together!

1?? How would you answer this question:

Given:

BiFunction<String, String, String> concat= (s1,s2)->s1+s2;
Function<String, Integer> length = s->s.length();
int result = concat.compose(length).apply( "Java ", "21" );
System.out.println(result);        

What is printed?

A) 7

B) 6

C) 0

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

The given code contains an issue that causes a compilation error. Let's analyze it step by step.

Code Analysis:

BiFunction<String, String, String> concat= (s1,s2)->s1+s2;
Function<String, Integer> length = s->s.length();
int result = concat.compose(length).apply( "Java ", "21" );
System.out.println(result);        

- 1. Understanding BiFunction<String, String, String>:

BiFunction<String, String, String> concat = (s1, s2) -> s1 + s2;

concat takes two String parameters (s1, s2) and returns a String (concatenation of the two).

- 2. Understanding Function<String, Integer>:

Function<String, Integer> length = s -> s.length();

length takes a String and returns its length (Integer).

- 3. Issue with compose Method:

concat.compose(length)

The compose method in Function<T, R> works as follows:

default <V> Function<V, R> compose(Function<? super V, ? extends T> before)

This means compose can only be used on unary functions (Function<T, R>), not BiFunction<T, U, R>.

Since concat is a BiFunction, it does not have a compose method, leading to a compilation error.

- Answer:

Since BiFunction does not have a compose method, compilation fails.

Thus, the correct answer is: E) Compilation fails.

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

(Working with Streams and Lambda expressions)




2?? How would you answer this question:

Given:

public class EnumConstructor{
    public static void main( String[] args ) {
        System.out.println(FrenchCheese.BRIE==FrenchCheese.CAMEMBERT);
    }
}

enum FrenchCheese {
    BRIE(5), CAMEMBERT(5), ROQUEFORT(20);

    private final int agingWeeks;

    public FrenchCheese(int agingWeeks ){
        this.agingWeeks = agingWeeks;
    }
    
}        

What is printed?

A) true

B) false

C) An exception is thrown at runtime.

D) Compilation fails.

#PathToJava21 #java #certification

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

?? Solution

The given code will fail to compile, so the correct answer is:

D) Compilation fails.

Explanation:

- Enum Constructor Issue:

public FrenchCheese(int agingWeeks) {

Enums in Java cannot have a public or protected constructor.

Enum constructors must be private. (Edit: thx Lew)

If you attempt to declare it as public, the compilation fails.

Error Message: The compilation error would be something like:

modifier 'public' not allowed here

- Corrected Code:

To fix the issue, change the constructor to private:

enum FrenchCheese {
    BRIE(5), CAMEMBERT(5), ROQUEFORT(20);

    private final int agingWeeks;

    FrenchCheese(int agingWeeks) { // Must be private (implicitly private)
        this.agingWeeks = agingWeeks;
    }
}        

Now, if you run the program, it will print:

false

Because FrenchCheese.BRIE and FrenchCheese.CAMEMBERT are distinct enum instances, even though they have the same agingWeeks value.

If the code were corrected, the correct answer would be B) false, but as given, the answer remains D) Compilation fails.

Enum Types: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

(Using Object-Oriented Concepts in Java)




3?? How would you answer this question:

Which are legal variable declarations? (choose 2)

A) var a;

B) int a = 1, int b = 2;

C) int a = b = 1;

D) int a = 1, b = 2;

E) int a; var b = (a = 7);

#PathToJava21 #java #certification

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

?? Solution

Let's analyze each option based on the given grammar rules.

Breakdown of the given grammar:

- A FieldDeclaration consists of:

{FieldModifier} UnannType VariableDeclaratorList ;

- A VariableDeclaratorList consists of:

VariableDeclarator {, VariableDeclarator}

- A VariableDeclarator consists of:

VariableDeclaratorId [= VariableInitializer]

- A VariableDeclaratorId consists of:

Identifier [Dims]

- A VariableInitializer allows for an assignment.

Now, let's evaluate each choice:

- A) var a;

var is a reserved keyword in Java, but it requires an initializer when used for type inference.

INVALID because var a; lacks an initializer.

- B) int a = 1, int b = 2;

The declaration includes int twice in a single statement.

INVALID because int should be specified only once before the first variable.

- C) int a = b = 1;

This relies on b being declared beforehand, which is not the case.

INVALID because b is used before being declared.

- D) int a = 1, b = 2;

VariableDeclaratorList allows multiple declarators, and b = 2 is a valid VariableDeclarator.

VALID ?

- E) int a; var b = (a = 7);

a is declared without initialization, but later assigned 7 in (a = 7), which is a valid expression.

var requires an initializer, and (a = 7) evaluates to 7, making it valid.

VALID ?

- Correct answers:

? D) int a = 1, b = 2;

? E) int a; var b = (a = 7);

[JLS] Field Declarations: https://docs.oracle.com/javase/specs/jls/se21/html/jls-8.html#jls-VariableDeclaratorList

(Using Object-Oriented Concepts in Java)




4?? How would you answer this question:

Given:

//Edit thanks Lew (double -> BigDecimal)
public class DataOutputStreamTest {
    static final String dataFile = "invoicedata";
    static final BigDecimal[] prices = {
            new BigDecimal("19.99"),
            new BigDecimal("9.99"),
            new BigDecimal("15.99"),
            new BigDecimal("3.99"),
            new BigDecimal("4.99")
    };

    public static void main(String[] args) throws IOException {
        try (var out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)))) {
            for (BigDecimal price : prices) {
                out.<INSERT CODE HERE>(price.toString());
            }
        }

        BigDecimal total = BigDecimal.ZERO;
        try (var in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)))) {
            while (true) {
                try {
                    BigDecimal price = new BigDecimal(in.<INSERT CODE HERE>());
                    total = total.add(price);
                } catch (EOFException e) {
                    break;
                }
            }
        }

        System.out.println("Total: " + total);
    }
}        

What should be inserted in <INSERT CODE HERE> placeholders?

A) writeInt, readInt

B) writeByte, readByte

C) writeUTF, readUTF

D) write, read

#PathToJava21 #java #certification

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

?? Solution

The correct answer is:

C) writeUTF, readUTF

Explanation:

- BigDecimal does not have a direct binary representation in DataOutputStream, we serialize it as a string using writeUTF.

- When reading the data back, we use readUTF, and then convert it back into a BigDecimal.

Why not the other options?

  • A) writeInt, readInt → Incorrect because BigDecimal is not an int, and storing decimal values as integers would lose precision.
  • B) writeByte, readByte → Incorrect because a BigDecimal cannot be represented as a single byte.
  • D) write, read → Incorrect because write and read work with raw bytes, which would make it hard to reconstruct the BigDecimal properly.

Thus, C is the correct choice. ?

Data Streams: https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html

(Using Object-Oriented Concepts in Java)




5?? How would you answer this question:

Given:

package tgv;

public class TGV {
    protected String name= "TGV";
}

//And given:

package tgv.international;

import tgv.TGV;

public class Eurostar extends TGV {
    public static void main( String[] args ) {
        TGV eurostar = new Eurostar();
        System.out.print(eurostar.name);
    }
}        

What will be printed?

A) Nothing

B) TGV

C) An exception is thrown at runtime.

D) Class TGV does not compile.

E) Class Eurostar does not compile.

#PathToJava21 #java #certification

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

?? Solution

The given code results in a compilation error. Let's analyze why.

Code Analysis:

* Class TGV (Base Class)

package tgv;
public class TGV {
    protected String name = "TGV";
}        

- The name variable is protected, meaning it can be accessed:

1. Within the same package (tgv).

2. By subclasses (even if they are in a different package).

* Class Eurostar (Subclass in Another Package)

package tgv.international;

package tgv.international;
import tgv.TGV;
public class Eurostar extends TGV {
    public static void main( String[] args ) {
        TGV eurostar = new Eurostar();
        System.out.print(eurostar.name);
    }
}        

- The issue is in the following line:

System.out.print(eurostar.name);

- Here, eurostar is declared as TGV, not Eurostar.

- Even though Eurostar extends TGV, protected members cannot be accessed through a superclass reference outside the package.

- Protected members can only be accessed within a subclass using this or a direct subclass reference.

* Why Does This Cause a Compilation Error?

- If you modify the code to use this.name within Eurostar, it would work:

System.out.print(((Eurostar) eurostar).name);

or

System.out.print(new Eurostar().name);

- But as written, eurostar.name is not accessible from a superclass reference outside the package.

* Correct Answer:

?? E) Class Eurostar does not compile.

Controlling Access to Members of a Class: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

(Using Object-Oriented Concepts in Java)




6?? How would you answer this question:

You increased some thread priorities while lowering others, but lower-priority threads rarely run.

What concurrency concept describes this phenomenon?

A) Deadlock

B) Livelock

C) Race condition

D) Starvation

#PathToJava21 #java #certification

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

?? Solution

The correct answer is D) Starvation.

Explanation:

Starvation occurs when lower-priority threads are unable to execute because higher-priority threads keep consuming CPU time.

In many systems, the thread scheduler favors higher-priority threads, potentially preventing lower-priority ones from running, leading to starvation.

To mitigate starvation, you can:

- Use fair scheduling algorithms that ensure all threads get CPU time.

- Implement priority aging, where long-waiting low-priority threads gradually increase in priority.

- Use thread pools or fair locks (e.g., ReentrantLock with fairness enabled in Java).

Why are the other options incorrect?

A) Deadlock → Happens when two or more threads wait on each other indefinitely, preventing progress.

B) Livelock → Threads keep responding to each other’s actions but make no real progress.

C) Race Condition → Occurs when multiple threads access shared resources unpredictably, leading to inconsistent results.

Starvation and Livelock: https://docs.oracle.com/javase/tutorial/essential/concurrency/starvelive.html

Deadlock: https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

An example of a race condition: https://blogs.oracle.com/javamagazine/post/java-thread-synchronization-raceconditions-locks-conditions

(Managing Concurrent Code Execution)




Alexandre Tavares

Senior Java Architect and Developer | Founder JavaLabs | Cambridge Master MCA / AI PhD candidate

13 小时前

Tintin knows best

Andrew Faust

Java | Spring Boot | Developer | Architect | Cloud | Navy Veteran

2 天前

As a follow up - what’s the primary downside in extensive use of the ol BigDecimal class? Can anyone guess? Hint - think thousands of computations per second!

Lew Bloch

Software That Fits

2 天前

"static final double[] prices" double is not a suitable type for currency or monetary values.

Lew Bloch

Software That Fits

2 天前

"Enum constructors must be private (or package-private by default)" is wrong. Enum constructors are always private. https://docs.oracle.com/javase/specs/jls/se23/html/jls-8.html#jls-8.9.2

要查看或添加评论,请登录

Vincent Vauban的更多文章

  • ?? Broken Object Property Level Authorization – API3:2023 ??

    ?? Broken Object Property Level Authorization – API3:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? Broken Authentication – API2:2023 ??

    ?? Broken Authentication – API2:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? BOLA – The #1 API Security Threat (API1:2023)

    ?? BOLA – The #1 API Security Threat (API1:2023)

    I'm kicking off a series of articles on API Security ?? to help us—developers ??????????—better understand and…

  • [VV110] The Java 21 Newsletter

    [VV110] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • ?2??4?? Java 24 features with Thiago

    ?2??4?? Java 24 features with Thiago

    (Thanks Thiago Gonzaga ) Here are some insights based on Thiago X content. Java 24: JEP 491 Boosts Virtual Threads! ??…

  • [VV109] The Java 21 Newsletter

    [VV109] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • [VV108] The Java 21 Newsletter

    [VV108] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

    2 条评论
  • [VV107] The Java 21 Newsletter

    [VV107] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • Communication Efficace #french

    Communication Efficace #french

    J'ai eu la chance de suivre un cours de communication grace à Zenika, une entreprise qui accorde une grande importance…

  • [VV106] The Java 21 Newsletter

    [VV106] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…