Are Java enums considered primitive or reference types?

Java

Java Problem Overview


If I have an enum object, is it considered a primitive or a reference?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

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.

Solution 3 - Java

This article essentially shows you how enums are implemented, and as SLaks says, they are references.

Solution 4 - Java

Enums are reference types, in that they can have methods and can be executed from command line as well , if they have main method.

See following "Planet" example from Sun/Oracle

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzer0stimulusView Question on Stackoverflow
Solution 1 - JavaSLaksView Answer on Stackoverflow
Solution 2 - JavaAlex VIView Answer on Stackoverflow
Solution 3 - JavaTofuBeerView Answer on Stackoverflow
Solution 4 - JavaK.MView Answer on Stackoverflow