
Enums are lists of constants
like unchangeable variables. Have you heard of Final keyword
? It’s like that.
When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. For instance, in a chess game you could represent the different types of pieces as an enum:
enum ChessPiece { PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING; }
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

Java Example:
package com.crunchify.tutorials; /** * @author Crunchify.com */ public class CrunchifyEnumExample { public enum Company { EBAY, PAYPAL, GOOGLE, YAHOO, ATT } Company cName; public CrunchifyEnumExample(Company cName) { this.cName = cName; } public void companyDetails() { switch (cName) { case EBAY: System.out.println("EBAY: Biggest Market Place in the World."); break; case PAYPAL: System.out.println("PAYPAL: Simplest way to manage Money."); break; case GOOGLE: case YAHOO: System.out.println("YAHOO: 1st Web 2.0 Company."); break; default: System.out.println("DEFAULT: Google - biggest search giant.. ATT - my carrier provider.."); break; } } public static void main(String[] args) { CrunchifyEnumExample ebay = new CrunchifyEnumExample(Company.EBAY); ebay.companyDetails(); CrunchifyEnumExample paypal = new CrunchifyEnumExample(Company.PAYPAL); paypal.companyDetails(); CrunchifyEnumExample google = new CrunchifyEnumExample(Company.GOOGLE); google.companyDetails(); CrunchifyEnumExample yahoo = new CrunchifyEnumExample(Company.YAHOO); yahoo.companyDetails(); CrunchifyEnumExample att = new CrunchifyEnumExample(Company.ATT); att.companyDetails(); } }
Output:
EBAY: Biggest Market Place in the World. PAYPAL: Simplest way to manage Money. YAHOO: 1st Web 2.0 Company. YAHOO: 1st Web 2.0 Company. DEFAULT: Google - biggest search giant.. ATT - my carrier provider.. Process finished with exit code 0
Some very important points on Java Enum:
Point-1
All enums implicitly extend java.lang.Enum
. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Point-2
Enum in Java are type-safe:
Enum has there own name-space. It means your enum will have a type for example “Company” in below example and you can not assign any value other than specified in Enum Constants.
public enum Company { EBAY, PAYPAL, GOOGLE, YAHOO, ATT } Company cName = Company.EBAY; cName = 1; // Compilation Error
Point-3
You can specify values of enum constants at the creation time. MyEnum.values()
returns an array of MyEnum’s values.
package com.crunchify.tutorial; /** * @author Crunchify.com */ public class CrunchifyEnumExample { public enum Company { EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25); private int value; private Company(int value) { this.value = value; } } public static void main(String[] args) { for (Company cName : Company.values()) { System.out.println("Company Value: " + cName.value + " - Company Name: " + cName); } } }
Output:
Company Value: 30 - Company Name: EBAY Company Value: 10 - Company Name: PAYPAL Company Value: 15 - Company Name: GOOGLE Company Value: 20 - Company Name: YAHOO Company Value: 25 - Company Name: ATT
Point-4
Enum constants are implicitly static and final and can not be changed once created.
Point-5
Enum can be safely compare using:
- Switch-Case Statement
- == Operator
- .equals() methodPlease follow complete tutorial.
Company eBay = Company.EBAY; if(eBay == Company.EBAY){ log.info("enum in java can be compared using =="); }
Point-6
You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
Point-7
Instance of Enum in Java is created when any Enum constants are first called or referenced in code.
Point-8
An enum specifies a list of constant values assigned to a type.
Point-9
An enum can be declared outside or inside a class, but NOT in a method.
Point-10
An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
Point-11
Enums can contain constructors, methods, variables, and constant class bodies.
Point-12
enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor.
Point-13
enum constructors can have arguments, and can be overloaded.
Point-14
enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
Point-15
The semicolon at the end of an enum declaration is optional.
These are legal:
enum Foo { ONE, TWO, THREE} enum Foo { ONE, TWO, THREE};
Another simple Java eNUM Example:
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum.
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
Between, overuse of enums might mean that your methods do too much (it’s often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.
This is very simple Java eNum Example
/** * @author Crunchify.com */ public enum CrunchifyEnumCompany { GOOGLE("G"), YAHOO("Y"), EBAY("E"), PAYPAL("P"); private String companyLetter; private CrunchifyEnumCompany(String s) { companyLetter = s; } public String getCompanyLetter() { return companyLetter; } } package com.crunchify.tutorials; import com.crunchify.tutorials.CrunchifyEnumCompany; /** * @author Crunchify.com */ public class CrunchifyEnumExample { public static void main(String[] args) { System.out.println("Get enum value for Company 'eBay': " + CrunchifyEnumCompany.EBAY.getCompanyLetter()); } }
Output:
Get enum value for Company 'eBay': Value: E
I am new to Java, can someone explain to me why for instance
CrunchifyEnumExample ebay = new CrunchifyEnumExample(Company.EBAY);
Why does the argument needs to be (Company.EBAY) instead of(EBAY)? thx
As you see you will have “Cannot resolve symbol ‘EBAY'” error if you remove Company.
I hope this clarifies.
https://uploads.disquscdn.com/images/5d920395ae83a82460ac099371e59556528880c4b0ccab01838e8789463f97a8.png
PFA 2 screenshots. A small typo on your part here, and beginners will get mis-guided.
If some one just reads google’s result, then his basics will go for a toss.
Please correct this.
https://uploads.disquscdn.com/images/a25b8ea0947f17b1931cd6ade0104741d7e152bf6f4682795496061f91fa01bd.png https://uploads.disquscdn.com/images/3ee3c07405e1dafaac83a5f06dccd8369ae280cc593d4d8432ca1ad6f5815085.png
And you are welcome 🙂
Thanks Ashutosh. I’ve just updated typo. Happy coding and keep visiting.
Any chance you could discuss reverse enum lookup? I have a problem where I unfortunately have to work with 2 databases and one database refers to my enum with one set of Strings and the other database in another way. I can get the, in your example, the company letter from the enum quite easily, but it is less easy to do it the other way around. Any thoughts?
I guess there should be not enums but a simple class.
edit: can anyone tell me how to mark the text below as code?
actually I found a pretty decent solution to this that only works in java 8, as my boss insists we use enums for this.
constructor of my enum looks like this:
and then I add a static method that looks like this:
Really nice..!
Thats awesome explanation. Thank you. I have a small question with using enum and using a java class and defining static variables.
For example we can define enum like :-
And for the same thing, we can use a java class with static variables like :-
And for calling both the classes we can do :-
I want to know what difference it will make or are those the alternative solutions to one another. 7
Thank you.
Good question Pranish. This is very big discussion but simple answer: ENUM is technically a Class construct with a bunch of typed constants. I would suggest to use an enum which will give you some methods like
Enum.valueOf
which you have available to use by default.Also using eNUM will give you all above mentioned advantages like Type and Value safety, Singleton ENUM, and so on.
Thank you for the answer. I came to know that ENUM consumes more memory than using a Java class with static variables. It was also recommended to avoid using ENUM for android as there is limited and small amount of memory. To how extend are things correct?
Thanks Pranish. I’ve very limited hands on experience on Android. I would like to play with it in the future and will try it out your theory. Happy coding.
“When you need a predefined list of values which do “not” represent some kind of numeric or textual data, you should use an enum” I think in the above sentence not has to be removed
Thank you. Updated Tutorial.
I’d like to thank you for that great Job!!! Congratulations.
Thanks Fernando for kind word. Happy coding.
The mistake in source code
“Comapny Name”
Hi Hleb. Thanks. Just fixed company name typo above.
For years Enums have been rubbing me off in a wrong way. There was some link, some piece of puzzle I was missing and always avoided them where possible, until this day when it all came clear with this one sentence:
“enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor”.
You could see a literal lightbulb on my head. Thanks a lot.
Hey Mike. I’m glad tutorial worked for you. Happy coding and keep visiting.
Thanks for the this good article
Instead of the Switch, provide an abstract method, then override it for each constant.
Nice article,
there are some more interesting operation on Enums I tried.
It may be helpful for some1.
Thanks Manish.
That’s an awesome work! Congratulations!
In the aforementioned post, the following point seems to be incorrect:
4) Enum constants are implicitly static and final and can not be changed once created.
public class EnumSingleton
{
enum MemoryManager
{
A(1), B(2);
private int var;
MemoryManager(int val)
{
this.var = val;
}
public int getVar()
{
return var;
}
public void setVar(int var)
{
this.var = var;
}
}
public static void main(String[] args)
{
for (MemoryManager m : MemoryManager.values())
{
m.setVar(100);
System.out.println(m + ” ” + m.var);
}
}
}
/* output:
A 100
B 100
*/
In above example if we do
MemoryManager.A = MemoryManager.B
then it will give us a compilation error aboutfinal
keyword.I’m in the middle of trying to write out an Enum article myself at codersnook . Great piece! I’ll refer to your article
Thanks David. Please share link once you publish your article.
Will do. I’ll be adding more content in the future. I have a few articles written and I’m planning on doing an article purge hopefully by end-of-monhth. Here’s the post:
http://codersnook.com/getting-started-with-java-learning-about-enums-and-writing-a-roman-numeral-converter/
Thanks David.
Great article to learn Enum. I would also suggest to read through following comprehensive 10 Enum Examples in Java and 15 Java Enum Interview Questions. Both of them provide good overview of different enum features.
Thanks for sharing.
This is exactly what I’m looking for. This blog is getting nice Java Tutorials. Keep doing the same.
Thanks,
Jaidip
Agree with you Jaidip. Waiting for some more tutorials Crunchify.
Thanks Jaidip and Marcus for kind words.. Added so many more examples already..