If I have an enum object, is it considered a primitive or a reference?
In some ways, an enum is similar to the boolean data type, which has true and false as its only possible values. However, boolean is a primitive type, while an enum is not.
Enum is Reference Type or Value Type? enumerations are of value type. They are created and stored on the stack and passed to the methods by making a copy of the value (by value). Enums are value type.
In Java you cannot pass any parameters by reference. The only workaround I can think of would be to create a wrapper class, and wrap an enum. Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
The way enums work is actually not too different from how they were used before their introduction with Java 5:
public final class Suit { public static final Suit CLUBS = new Suit(); public static final Suit DIAMONDS = new Suit(); public static final Suit HEARTS = new Suit(); public static final Suit SPADES = new Suit(); /** * Prevent external instantiation. */ private Suit() { // No implementation }}
By instantiating the different suits on class loading it is ensured that these will be mutually exclusive and the private constructor ensures that no further instances will be created.
These would be comparable either through == or equals.
The Java 5 enum works pretty much the same way, but with some necessary features to support serialization etc.
I hope this background sheds some further light.
It's a reference type. Java primitives are boolean byte short char int long float double
.
You can get the enumeration constant's value by calling ordinal()
, which is used by EnumSet and EnumMap iterator
and "traverses the elements in their natural order (the order in which the enum constants are declared)"
You can even add your own members to the enum class, like this:
public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); } //Elsewhere: Operation op = Operation.PLUS; double two = op.eval(1, 1);
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