This is more of a design question, so no code. I could post code of creating an Enum and assigning it to null
if you want me to do it. :))
I've been thinking a lot about this lately, but can't come up with one good reason. The Enum constants are implicitly static and final. Enum is meant to say - "I can take a value of one of the constants present in me". Why allow Enum to have a null
value? Why not implicitly default the Enum's value to a Enum.DEFAULT
or Enum.None
? Isn't this a better approach than allowing the Enum to be null
?
NOT NULL − In ENUM type, by default NULL values are allowed. To disallow NULL values, we need to use the NOT NULL attribute while describing the ENUM column.
By default enums have their own string values, we can also assign some custom values to enums.
If an ENUM column is declared to permit NULL , the NULL value is a valid value for the column, and the default value is NULL . If an ENUM column is declared NOT NULL , its default value is the first element of the list of permitted values.
Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.
Firstly null
means non-existence of an instance. Providing a default constant like DEFAULT
or NONE
, will change that meaning. Secondly, why would you need something default to represent what seems to be non-existent? That is the purpose of null
. Basically, you would have to initialize and store an extra object, which shouldn't even exist whatsoever.
BTW, it's not a language choice. It's completely on you how you implement your enum. You can provide another constant like DEFAULT
, or UNKNOWN
in your enum, and avoid the assignment of null
to the reference in your code. This is famously known as Null Object Pattern. But saying that the null
assignment should itself be compiler error, then I would say, since an Enum
is anyways compiled to a Class
, so it would be perfectly valid to use null
to represent non-existence of an instance.
One pitfall of allowing null
though is with the usage of enum
in switch-case
. The below code will throw NPE
, even with a default
case:
public class Demo { enum Color { WHITE, BLACK; } public static void main(String[] args) { Color color = null; switch (color) { // NPE here case WHITE: break; case BLACK: break; default: break; // null value does not fall into the default } } }
Java does not allow a case null:
either, producing the following compile error:
an enum switch case label must be the unqualified name of an enumeration constant
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With