Reputation: 3206
While switch(null)
is a compile error but switch(str)
is fine (str
being static final String str = null;
).
Isn't static final String str = null;
a compile-time constant which shall be substituted into switch(str)
at compile time and thus be equivalent to switch(null)
?
switch (null) { // compile Error immediately!
}
BUT:
public class Test {
// compile-time constant?
static final String s4 = null;
public static void main(String[] args) {
switch (s4) { // compiles fine! NPE at runtime
}
}
}
P.S. I suppose static final String str = null;
IS NOT a compile-time constant, because only static final String str = 'string literal'
is a compile-time constant, which explains example above (s4).
Upvotes: 3
Views: 114
Reputation: 19911
From the error message:
Incompatible types. Found 'null', required: 'char, byte, short, int, Character, Byte, Integer, String, or an enum'
You can see that null
is inferred to nothing, it's not even an Object
, it is simply the "null type", and not a String
(or any other valid switchable type).
So for it to compile you'd need to cast it to String
(or one of the other valid types).
switch((String) null) {
Which then throws a RuntimeException
when you try to execute it.
This behaviour is not only applicable to switch
it is in fact the same as when you do this:
null.isEmpty()
How should java know that you want to invoke String#isEmpty()
? You could aswell mean Collection#isEmpty()
. Or any other isEmpty()
method. The same goes for the switch
-example, java simply doesn't know which type you mean.
Upvotes: 7
Reputation: 19618
From Oracle's doc:
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
Hence switch(null)
is invalid because you can't switch on any value (null
could be a null Banana
object which is not supported)
Upvotes: 3