Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum field named "float"

Tags:

java

enums

I have a code generator which generates enums based on some user-defined names. For some reason, if a user defines an enum with field e.g. "float", "switch" or some other compiler specific keyword, Java complains.

For example, I would like to define an enum with two fields "float" and "switch":

public enum TestEnum {
    float(100), switch(200);
}

However, Java thinks that it is some float variable and it does not understand the switch variable at all.

In C (if I am not mistaken) this makes no problem

enum TestEnum {
    float  = 100,
    switch = 200,
};

Is it possible to use such "names" for the enums somehow?

like image 525
pisoir Avatar asked May 30 '26 06:05

pisoir


2 Answers

float and switch are keywords in Java and cannot be used as enum values. I recommend following conventions and making them uppercase (i.e. FLOAT, SWITCH).

public enum TestEnum {
    FLOAT(100),
    SWITCH(200);

    TestEnum(int value) {

    }
}
like image 86
Jacob G. Avatar answered May 31 '26 20:05

Jacob G.


It's not possible in java. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Also the code style implies using of UPPER (divided by _ if necessary) case names for enum constansts.

like image 35
Bogdan Lukiyanchuk Avatar answered May 31 '26 19:05

Bogdan Lukiyanchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!