Passing null as a switch parameter in Java will cause an exception - Java syntactic sugar

question

The switch parameter cannot be null, switch(null) will report java.lang.NullPointerException
insert image description here

Find out why

Why is this happening? Find out the reason:
find the compiled class file, you will understand

insert image description here

Summarize:

switch is a syntactic sugar. The switch statement first calculates the sorted value of the param variable and then compares it with each sorted value of the enumeration constant.

The switch(param) in the source code calls the hashCode method of String.

The switch method only supports matching of int types, other basic types will be converted to integer types by syntactic sugar for judgment and matching.

To sum up, the java switch parameter cannot be null, and switch(null) will report java.lang.NullPointerException.

expand

Other syntactic sugar for Java

Syntactic Sugar, also known as sugar-coated grammar, is a term coined by British computer scientist Peter J. Landin. It refers to adding a certain grammar to the computer language, which can make it easier for programmers to use the language to develop programs, while enhancing the readability of the program code and avoiding the chance of errors; but this grammar affects the function of the language. did not affect.

Generics:

Compared with generics in C#, Java's generics can be regarded as "pseudo-generics". In C#, generics are real, whether in the program source code, in the compiled intermediate language, or in the runtime. Java is different. Java's generics only exist in the source code and are only used for editor inspection. The compiled bytecode file has erased the generic type, and inserted cast code where necessary.

Automatic unboxing and packing:

Automatic unboxing/boxing is to decide whether to perform unboxing and boxing according to the syntax of the code at compile time.

Boxing process: The basic types are packaged with their corresponding packaging types, so that the basic types have object characteristics.

Unboxing process: In contrast to the boxing process, the wrapper type is converted to a primitive type.

foreach loop:

Foreach requires that the object to be traversed implements the Iterable interface. As you can imagine, foreach iteration is also implemented by calling the underlying iterator.

enumerate:

The enumeration type is actually not complicated. There is no "enumeration" type in the JVM bytecode file structure. In fact, the enumeration type of the source program will be compiled into a common class at compile time. Use inheritance and reflection to do it.

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/123297530