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
[HD-OCP17/21-Fundamentals Pg 287, Sec. 12.3.2 - the-selector-expression]
Moderator: admin
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
-
- 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]
No, it is correct. default does not necessarily have to be present if case null is present. For example, the following works:
The book correctly notes :
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;
};
}
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.
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
Re: [HD-OCP17/21-Fundamentals Pg 287, Sec. 12.3.2 - the-selector-expression]
yes you right sorry!
Who is online
Users browsing this forum: No registered users and 4 guests