Let’s start with C#. In C# nulls may show up in switch statement in two cases:
We switch on string type
We switch on nullable char, nullable integral type (byte, short etc.)
or nullable enum
Both cases are handled by compiler in the same way,
we just declare case null label and it will work out of the box.
This is illustrated by simple program:
Java switch and null’s
In Java null’s may show up in switch statement when we switch
on primitive type wrappers like Integer or on String or on enum type.
In that case Java will throw NullPointerException as is demonstrated by program:
As we have seen it’s not even possible to declare case null label.
In Java until you are 100% sure that value will not contain null you must
explicitly check for null before switch as in:
Or use trick with default value:
WARNING: This Java behaviour may cause problems when we translate code from C# to Java.
an expression that will be evaluated at runtime. To compare case label values to
labels. Only tricky thing is with NaNs because NaN === NaN yields false
numbers representation and behaviour.
In other words we can use NaN as a case label but
program will never enter block of code associated with that label. As a side note
the only value for which expression x === x yields
This program will write:
Notice that "default" was printed for NaN value.
That’s all for today, I hope you learned something new from this article.
May the Force be with you.