[HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
joaoclopes
Posts: 26
Joined: Mon Sep 23, 2024 4:49 pm
Contact:

[HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Post by joaoclopes »

Hello! Regarding the 5. do I have a better way to solve it than this?

Code: Select all

// Switch statement without pattern matching
if (obj instanceof String) {
    String str = (String) obj;
    switch (str.charAt(0)) {
        case 'a':
            iVal = 96;
            break;
        case 'A':
            iVal = 65;
            break;
        default:
            iVal = 0;
    }
} else {
    iVal = 0;
}

// Switch statement with pattern matching
switch (obj) {
    case String value
            when value.startsWith("a") -> iVal = 96;
    case String value
            when value.startsWith("A") -> iVal = 65;
    default -> iVal = 0;
}

// Switch expression without pattern matching
if (obj instanceof String) {
    String str = (String) obj;
    iVal = switch (str.charAt(0)) {
        case 'a' -> 96;
        case 'A' -> 65;
        default -> 0;
    };
} else {
    iVal = 0;
}

// Switch expression with pattern matching
iVal = switch (obj) {
    case String value
            when value.startsWith("a") -> 96;
    case String value
            when value.startsWith("A") -> 65;
    default -> 0;
};
Thanks!
João

admin
Site Admin
Posts: 10326
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Post by admin »

Sorry for the late reply. That's good solution. Good job :thumbup:
If you like our products and services, please help us by posting your review here.

joaoclopes
Posts: 26
Joined: Mon Sep 23, 2024 4:49 pm
Contact:

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Post by joaoclopes »

No problem! Thanks for the feedback! :thumbup:

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests