[HD-OCP17/21-Fundamentals Pg 287, Sec. 12.3.2 - the-selector-expression]

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

Moderator: admin

Post Reply
raphaelzintec
Posts: 167
Joined: Sun Apr 21, 2024 10:43 am
Contact:

[HD-OCP17/21-Fundamentals Pg 287, Sec. 12.3.2 - the-selector-expression]

Post by raphaelzintec »

this is not true

"But if you use null in a switch label you need to use it before the default label (if the default
label is present)"

-> to use null value default label must always be present

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

Re: [HD-OCP17/21-Fundamentals Pg 287, Sec. 12.3.2 - the-selector-expression]

Post by admin »

No, it is correct. default does not necessarily have to be present if case null is present. For example, the following works:

Code: Select all

    static abstract sealed class Base permits Sub1, Sub2{
    }
    final static class Sub1 extends Base{
    }
    final static class Sub2 extends Base{
    }
    public static void main(String[] args) {
        Base b = new Sub1();
        int i = switch(b){
            case Sub1 s1 -> 0;
            case Sub2 s2 -> 1;                
            case null ->2;
        };
    }
The book correctly notes :
But if you use null in a switch label you need to use it before the default label (if the default label is present) and the switch statement must be exhaustive.


Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 12 guests