EN
Java switch with null - how to handle it?
0 answers
3 points
How do I handle null in switch statement in java?
For example when I have class like this:
xxxxxxxxxx
1
public class SwitchWithNull {
2
3
public static void main(String[] args) {
4
String name = null;
5
switch (name) {
6
case null: {
7
System.out.println("Case 1");
8
}
9
}
10
}
11
}
With this example when I try to compile it I have 2 compilation errors from Intellij Idea:
- Dereference of 'name' will produce 'NullPointerException'
screenshot:
- Constant expression required
The question is - what is the correct way of handling the null in switch statement in java?
I know that I can use if statement, but what about switch with null?
0 answers