[VV102] The Java 21 Newsletter

[VV102] The Java 21 Newsletter

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

How would you answer this question:

Given:

var mapOfCEOs = new HashMap<>();

mapOfCEOs.put( "Sundar Pichai", "Google" );
mapOfCEOs.put( "Tim Cook", "Apple" );
mapOfCEOs.put( "Mark Zuckerberg", "Meta" );
mapOfCEOs.put( "Andy Jassy", "Amazon" );        

Does the code compile?

A) True

B) False

#PathToJava21 #java #certification

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

?? Solution

True

The code compiles because var infers the type of mapOfCEOs as HashMap<Object, Object>.

This happens due to the diamond operator (<>), which defaults to the raw type when no explicit type is provided.

The put method accepts String arguments, which are subtypes of Object, making the calls valid.

Note 1: This is type erasure, not strict type inference, and specifying HashMap<String, String> explicitly is better for type safety.

Note 2: Type erasure in Java removes all generic type information during compilation, replacing type parameters with their bounds (or Object if none are specified).

This ensures backward compatibility and enforces type safety at compile time, but at runtime, all generics are treated as raw types (e.g., List<String> and List<Integer> both become List).






Given:

record WithInstanceField(String foo, int bar) {
    double fuz;
}

record WithStaticField(String foo, int bar) {
    static double wiz;
}

record ExtendingClass(String foo) extends Exception {}

record ImplementingInterface(String foo) implements Cloneable {}        

Which record(s) compile? (Select 2)

A) WithInstanceField

B) WithStaticField

C) ExtendingClass

D) ImplementingInterface

#PathToJava21 #java #certification

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

?? Solution

Let's explore one record at a time:

record WithInstanceField(String foo, int bar) {
    double fuz;
}        

Does not compile because the Instance field 'fuz' is not allowed in the record.

record WithStaticField(String foo, int bar) {
    static double wiz;
}        

Does compile.

record ExtendingClass(String foo) extends Exception {}        

It does not compile because no extends clause is allowed for record.

record ImplementingInterface(String foo) implements Cloneable {}        

Does compile.

Details on JEP 395: https://openjdk.org/jeps/395






Given:

interface SmartPhone {
    boolean ring();
}

class Iphone15 implements SmartPhone {
    boolean isRinging;
    boolean ring() {
        isRinging = !isRinging;
        return isRinging;
    }
}        

Choose the right statement.

A) SmartPhone interface does not compile

B) Iphone15 class does not compile

C) Everything compiles

D) An exception is thrown at running Iphone15.ring();

#PathToJava21 #java #certification

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

?? Solution

Correct Answer: B) Iphone15 class does not compile

Explanation:

In the provided code:

  • SmartPhone Interface

The SmartPhone interface declares a method boolean ring();

This compiles correctly because there is nothing wrong with the syntax or definition of the interface.

  • Iphone15 Class

The Iphone15 class implements the SmartPhone interface but defines the ring() method with default (package-private) access.

According to Java rules, methods implementing an interface must have the same or greater access visibility than the interface method. Since ring() in the SmartPhone interface is implicitly public, the overriding ring() method in the Iphone15 class must also be declared public.

As written, the Iphone15 class does not compile because the ring() method attempts to reduce the access level, which is not allowed.

  • Other Options

A) The SmartPhone interface compiles correctly, so this is incorrect.

C) Not everything compiles; the Iphone15 class has a compilation error.

D) Since the code doesn’t compile, an exception cannot be thrown at runtime.

  • Key Point:

The error message is:

'ring()' in 'Iphone15' clashes with 'ring()' in 'SmartPhone'; attempting to assign weaker access privileges ('package-private'); was 'public'.        






Given:

var now = LocalDate.now();

var format1 = new DateTimeFormatter( ISO_WEEK_DATE );

var format2 = DateTimeFormatter.ISO_WEEK_DATE;

var format3 = new DateFormat( WEEK_OF_YEAR_FIELD );

var format4 = DateFormat.getDateInstance( WEEK_OF_YEAR_FIELD );

System.out.println( now.format( REPLACE_HERE ) );        

Which variable prints 2025-W01-2 (present-day is 12/31/2024).

A) format1

B) format2

C) format3

D) format4

#PathToJava21 #java #certification

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

?? Solution

Correct Answer: B) format2

Explanation:

var format1 = new DateTimeFormatter(ISO_WEEK_DATE);        

This does not compile because there is no such constructor in the DateTimeFormatter class.

var format2 = DateTimeFormatter.ISO_WEEK_DATE;        

This compiles successfully.

ISO_WEEK_DATE is a predefined constant in the DateTimeFormatter class that formats dates according to the ISO-8601 week-based calendar system.

var format3 = new DateFormat(WEEK_OF_YEAR_FIELD);        

This does not compile because DateFormat is an abstract class and cannot be directly instantiated.

var format4 = DateFormat.getDateInstance(WEEK_OF_YEAR_FIELD);        

This does not work as expected because DateFormat does not provide functionality to format a LocalDate instance in this manner.

So,

When calling now.format(REPLACE_HERE) with the correct formatter,

format2 (which is DateTimeFormatter.ISO_WEEK_DATE) successfully formats the date 2024-12-31 into the ISO week date format: 2025-W01-2.

DateTimeFormatter: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatter.html

DateFormat: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/text/DateFormat.html






Given:

DoubleStream doubleStream = DoubleStream.of( 3.3, 4, 5.25, 6.66 );

Predicate<Double> doublePredicate = d -> d < 5;

System.out.println( doubleStream.anyMatch( doublePredicate ) );        

What is printed?

A) true

B) false

C) 3.3

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 correct answer is: E) Compilation fails

Explanation:

  • DoubleStream and Primitive Streams:

DoubleStream is part of Java's primitive streams API, specifically designed to handle double primitives directly, avoiding boxing overhead.

Methods like anyMatch in DoubleStream accept predicates designed for double primitives, not boxed Double objects.

This requires a DoublePredicate instead of a generic Predicate<Double>.

  • Type Mismatch:

The code attempts to use a Predicate<Double> (a generic functional interface) with DoubleStream.anyMatch.

However, DoubleStream.anyMatch expects a DoublePredicate (a specialized functional interface for double).

As a result, the code does not compile due to the type mismatch.

  • Error at Compile Time:

The compiler will generate an error like:

incompatible types: Predicate<Double> cannot be converted to DoublePredicate        

  • Correcting the Code:

To fix the compilation error, use a DoublePredicate instead of a Predicate<Double>:

DoubleStream doubleStream = DoubleStream.of(3.3, 4, 5.25, 6.66);

DoublePredicate doublePredicate = d -> d < 5;

System.out.println(doubleStream.anyMatch(doublePredicate));        

This corrected code will compile and print true, as 3.3 is less than 5.

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

DoubleStream: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/DoubleStream.html




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

Vincent Vauban的更多文章

  • [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:…

  • ???Jchampionsconf Day 4??

    ???Jchampionsconf Day 4??

    ????? Java, Code Coverage and their best friend – bytecode by Evgeny ?Take a deep dive into Java bytecode and ?uncover…

  • ???JCHAMPIONSCONF DAY 3??

    ???JCHAMPIONSCONF DAY 3??

    ?? Embracing Microservices Evolution By Mohamed ?Discover how “tactical forking” ?transforms the challenges of…

  • Mutation testing

    Mutation testing

    Mutation testing is a software testing technique used to evaluate the quality of test cases by intentionally…

社区洞察

其他会员也浏览了