Page 1 of 1

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

Posted: Wed Sep 25, 2024 1:42 am
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

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

Posted: Wed Sep 25, 2024 7:14 am
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.

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

Posted: Wed Sep 25, 2024 7:39 am
by raphaelzintec
yes you right sorry!