Wednesday, March 12, 2008

Java 1.5 Explained - Enum

Before Java 1.5, you'd probably write code like the following to implement enumerated types, similar to how it would be done in C using #define:
public final static int SUIT_CLUBS = 1;
public final static int SUIT_DIAMONDS = 2;
public final static int SUIT_HEARTS = 3;
public final static int SUIT_SPADES = 4;

Sure this is a little better than #define, but not much better. Java 1.5 enumerated types are similar to what's available in C++. Here's a C++ example:

enum Suit {
CLUBS = 1,
DIAMONDS = 2,
HEARTS = 3,
SPADES = 4
};
In Java this would be:
enum Suit {
CLUBS(1),
DIAMONDS(2),
HEARTS(3),
SPADES(4)
};
There's a subtle different between the Java and C++ syntax. Java is using parens to initialize the individual enumerated type entries to a specific value. What's really going on here? Let's take a look a some byte code.

First, here is a complete sample of some Java code using enum:
public class Enum
{
public enum Direction { NORTH, SOUTH, EAST, WEST };

public static void main(String[] args)
{
Direction d = Direction.EAST;
System.out.println(d);
}
}
And the corresponding byte code:
public class Enum extends java.lang.Object{
public Enum();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);
Code:
0: getstatic #2; //Field Enum$Direction.EAST:LEnum$Direction;
3: astore_1
4: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
7: aload_1
8: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
11: return
}
Look at line 0 in the main method. The Direction enum is really a Java class (in this case an inner class within this Enum class example) and it has a static field named EAST. Looking a little closer you can see that the field EAST is also Direction object. That explains the reason for having the parens to initialize the enumerated value. It's actually passing the value to a constructor. Now here's the bytecode for the Direction class that was automatically created:

public final class Enum$Direction extends java.lang.Enum{
public static final Enum$Direction NORTH;

public static final Enum$Direction SOUTH;

public static final Enum$Direction EAST;

public static final Enum$Direction WEST;

public static final Enum$Direction[] values();
Code:
0: getstatic #1; //Field $VALUES:[LEnum$Direction;
3: invokevirtual #2; //Method "[LEnum$Direction;".clone:()Ljava/lang/Object;
6: checkcast #3; //class "[LEnum$Direction;"
9: areturn

public static Enum$Direction valueOf(java.lang.String);
Code:
0: ldc_w #4; //class Enum$Direction
3: aload_0
4: invokestatic #5; //Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
7: checkcast #4; //class Enum$Direction
10: areturn

static {};
Code:
0: new #4; //class Enum$Direction
3: dup
4: ldc #7; //String NORTH
6: iconst_0
7: invokespecial #8; //Method "":(Ljava/lang/String;I)V
10: putstatic #9; //Field NORTH:LEnum$Direction;
13: new #4; //class Enum$Direction
16: dup
17: ldc #10; //String SOUTH
19: iconst_1
20: invokespecial #8; //Method "":(Ljava/lang/String;I)V
23: putstatic #11; //Field SOUTH:LEnum$Direction;
26: new #4; //class Enum$Direction
29: dup
30: ldc #12; //String EAST
32: iconst_2
33: invokespecial #8; //Method "":(Ljava/lang/String;I)V
36: putstatic #13; //Field EAST:LEnum$Direction;
39: new #4; //class Enum$Direction
42: dup
43: ldc #14; //String WEST
45: iconst_3
46: invokespecial #8; //Method "":(Ljava/lang/String;I)V
49: putstatic #15; //Field WEST:LEnum$Direction;
52: iconst_4
53: anewarray #4; //class Enum$Direction
56: dup
57: iconst_0
58: getstatic #9; //Field NORTH:LEnum$Direction;
61: aastore
62: dup
63: iconst_1
64: getstatic #11; //Field SOUTH:LEnum$Direction;
67: aastore
68: dup
69: iconst_2
70: getstatic #13; //Field EAST:LEnum$Direction;
73: aastore
74: dup
75: iconst_3
76: getstatic #15; //Field WEST:LEnum$Direction;
79: aastore
80: putstatic #1; //Field $VALUES:[LEnum$Direction;
83: return
}
There's a lot going on in Direction. It's really just a bunch of code which could have been written by hand prior to Java 1.5, but now the compiler is doing all the work for us. The code is basically doing this:
public class Direction extends java.lang.Enum
{
public final static Direction NORTH;
public final static Direction SOUTH;
public final static Direction EAST;
public final static Direction WEST;

static
{
NORTH = new Direction("NORTH", 0);
SOUTH = new Direction("SOUTH", 1);
EAST = new Direction("EAST", 2);
WEST = new Direction("WEST", 3);

VALUES = new Direction[4];
VALUES[0] = NORTH;
VALUES[1] = SOUTH;
VALUES[2] = EAST;
VALUES[3] = WEST;
}
}
How about that? All that code came from pretty much one line of code in Java 1.5. Notice also that Direction extends a new class in Java 1.5, java.lang.Enum. This new class is where the String and oridinal values for the enumerated type are stored. Now you can see where the nice toString() comes from with enumerated types. In our example above, the System.out.println(d) will print "EAST". The Enum.ordinal() method can be used to get the ordinal value as well.

There's a lot more you can do with enum, like add your own methods that will be included in the class that's automatically generated. Please see Sun's Enum page for more information.

63 comments:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Java String to Integer said...

Enum in Java is a convenient feature Which should have been introduced When Java earliar. At same time Enum is very versatile and you can do lot more than just representing value.See this article 10 Examples of Enum in Java which is quite exhaustive in terms of enum features.

Unknown said...

Great And Useful Article

Online Java Training from India

Java Training Institutes in Chennai

Anonymous said...

Nice article explaining the fundamentals of Java enums. Here is another tutorial on java enums which explains enums and also shows how to use the various utility methods in enums with code examples - http://www.javabrahman.com/corejava/the-complete-java-enums-tutorial-with-examples/

Anonymous said...

The Complete Java Enums tutorial by JavaBrahman.com

gowsalya said...

Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.
python training in chennai
python course institute in chennai

jai said...

A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
Data Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in kalyan nagar

sheela said...

I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
Best Devops Training in pune
Devops Training in Bangalore
Microsoft azure training in Bangalore
Power bi training in Chennai

jefrin said...

Amazing blog thanks for sharing
Best power BI training course in chennai

swashthik said...

This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.

Ajith said...

Great article !!
Thanks for sharing this valuable information!
Considering visiting www.apponix.com
This is the No 1. training institute in Bangalore.

digitalsourabh said...

C C
++ Classes in Bhopal

Nodejs Training in Bhopal
Big Data Hadoop Training in Bhopal
FullStack Training in Bhopal
AngularJs Training in Bhopal
Cloud Computing Training in Bhopal
PHP Training in Bhopal

Techxinx said...



Thanks for sharing excellent information.If you Are looking Best smart autocad classes in india,
provide best service for us.
autocad in bhopal
3ds max classes in bhopal
CPCT Coaching in Bhopal
java coaching in bhopal
Autocad classes in bhopal
Catia coaching in bhopal

unknow said...

I really enjoyed your blog Thanks for sharing such an informative post.
https://myseokhazana.com/
https://seosagar.in/
Indian Bookmarking list
Indian Bookmarking list
India Classified Submission List
Indian Classified List
Indian Bookmarking list
Indian Bookmarking list
India Classified Submission List
Indian Classified List


Anonymous said...

For Devops Training in Bangalore Visit: Devops training in Bangalore

Training for IT and Software Courses said...

Wow it is really wonderful and awesome thus it is veWow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.microsoft azure training in bangalore

vijay said...

thanks for this informative article it is very useful

aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

hami said...

I am obliged to you for sharing this piece of statistics
here and updating us together with your inventive steerage.
tamilgun movies

aj said...
This comment has been removed by the author.
aj said...

Snapdeal Winner List here came up with an Offer where you can win Snapdeal prize list 2020 by just playing a game & win prizes.
Snapdeal winner name2020 also check the Snapdeal lucky draw2020

GlobalEmployees said...

Read my post here
Global Employees
Global Employees
Global Employees

Rajesh Anbu said...

Really nice post. Thank you for sharing amazing information.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

hami said...

Click here to more info

shopclueswinner said...

Shopclues lucky draw 2020| Shopclues winner 2020|Get to Know Shopclues Lucky Draw Winner 2020. Call Shopclues Helpline Phone Number+91-9835565523 for Shopclues Online Shopping Lucky Draw.
Shopclues online lucky draw winner
Shopclues winner 2020
shopclues car lucky draw

snapdeal services said...

Snapdeal winner 2020 | Dear customer, you can complain here If you get to call and SMS regarding Snapdeal lucky draw, Mahindra xuv 500, lucky draw contest, contact us at to know the actual Snapdeal prize winners 2020.
Snapdeal winner 2020
Snapdeal lucky draw winner 2020
Snapdeal lucky draw contest 2020
snapdeal winner prizes 2020

Shivaraj said...

I am glad to read that you come up with outstanding information that definitely allows me to share with others. Thank you for sharing this with us.

digital marketing coaching in hubli

nisha said...

Thanks for sharing this wonderful blog. the blog is very Impressive. every contents are very uniquely represented.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

Anonymous said...

Awesome read, keep up the great work! for more Tutorials

Anonymous said...

Nice blog.
reactjs training in bangalore
azure training in bangalore
pcb design training in bangalore

svrtechnologies said...

That is nice article from you , this is informative stuff . Hope more articles from you . I also want to share some information about devops training in pune

mukesh said...

Shopclues Lucky Draw

Indian electronic commerce company in Bengaluru, India is basically referred to as Shopclues Private Limited. Shopclues Private Limited is a company founded by Rohit Bansal and Kunal Bahl a few years back in 2010. The main aim of this Bengaluru based electronic commerce company is to focus on book sales, electronic equipment, and clothes. Therefore, the sales of these three things are the prime focus of Shopclues Private Limited Company. Hence, before expanding other categories such as consumer electronics, fashion, lifestyle, etc. the company did a good job in all the above mentioned three things.


Probing further, Shopclues Private Limited has now decided to open a Jackpot Shopclues Lucky Draw Contest for all the buyers using this company for having exciting products. The winner of this Jackpot contest will get so many exciting gifts but the only thing the users will have to do is to shop things from the company. We can say that this is a global opportunity for people to have expensive prizes that are not easily affordable to them.

The first prize for this contest is Tata Safari Car.
The second prize for Snapdeal Lucky Draw Contest is Swift Desire Car.
The third prize for this jackpot contest is KTM Sports Bike.

People can easily grab these jackpot prizes by participating in the lucky draw contest. So, what are you waiting for go and start shopping today only? Ergo, don’t forget to participate in the Snapdeal Lucky Draw contest as it can change your shopping philosophy totally. To know more about the further things you can check out the site.

Sekhar Sahu said...

This is excellent information. It is amazing and wonderful to visit your site. Thanks for sharing this information, this is useful to me...

Looking for the best PPC course in Bangalore India? Learn PPC from Ranjan Jena, 10+ Years Expert Google Ads Trainer. 1000+ Students Trained @ eMarket Education, Koramangala, Bangalore.
Best Online Digital Marketing Courses in Bangalore, India
Best Digital Marketing Institute in Bangalore

eMarket Education said...

Very interesting article to read it. I would like to thank you for the efforts you had made for writing this wonderful article. This article inspired me to read more. Keep sharing on updated posts…

Learn Digital Marketing Course in Bangalore with Live Project Work & Case Studies taught by Ranjan Jena (10Yrs Trainer). 100% Guarantee to Clear Job Interview

Franklin said...

best learning management system
online learning management system software
google meet alternative

Shivam Kumar said...

You have explained the topic very well. Thanks for sharing a nice article.Visit Nice Java Example

abhishek mondal said...

Mother dairy franchise
Mother Dairy Franchise: Dairy has become a part of Indian food culture. It does not matter whether it is breakfast, lunch or dinner, dairy is always present in one form or the other. It can be in the form of milk, curd, cottage cheese or just some ice cream after dinner. Mother Dairy is a brand that has made a place for itself in the dairy sector. With its wide range of good quality products, it has managed to gain a loyal customer base. By adhering to its tagline ‘Happy Food, Happy People’. Mother dairy, with its diverse range of products, has been successfully managing to cater to people of all ages and all demographics. Continuously growing at a rapid pace, the company is letting its presence known in various big cities of the country and especially in the north part of India.

ram said...

David Forbes is president of Alliance Marketing Associates IncIamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder

Anonymous said...

Very nice article. I have gotten a lots of knowledge on about website directory submission. Excellent site lists.
https://motherdairydistributor.network/Mother-dairy-dealership.php

w3 web designs said...

Very nice article. I have gotten a lots of knowledge on about website directory submission. Excellent site lists. Thanks for share.Sir give me some tips how to improve my website ranking in search engines. Thanks again & keep up the good work

http://w3webdesigns.com/

lkrasilnikovaludmila1976 said...

Annabelle loves to write and has been doing so for many years.Backlink Indexer My GPL Store Teckum-All about Knowledge

salome said...

informative article.thank you.Angular training in Chennai

ram said...

Annabelle loves to write and has been doing so for many years.BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE BUY SEO SERVICE

Ashwini said...

nice informative post. Thanks you for sharing.
Wordpress Development
Mobile App Development

Anonymous said...

This blog is very helpful as sharing a huge list of sites.Thanks, for the list.

Abhishek said...

I really enjoyed this post. I appreciate your work on this gives in-depth information. I am really happy with the quality of learning tips for Beginners in this article. Thanks for sharing.
Java Classes in Bangalore

Unknown said...

what is contrave

silicon wives

sky pharmacy

atx 101 uk

macrolane buttock injections london

hydrogel buttock injections

buying vyvanse online legit

buy dermal fillers online usa

mesotherapy injections near me

xeomin reviews

Valluva said...

payroll software
organic chemistry tutor

Valluva said...

Thanks For Your Blog
Organic Chemistry

vishnu said...

Amazing write-up! Really Good.
Now the foundation of any business is digital marketing. Adsify marketing is the best Digital marketing in Trivandrum.

tamizhasolution said...

nice post..
Social Media Discount Deals

French language classes in Chennai said...

Thanks for the blog, Its good and valuable information.
Japanese Language Course | Japanese Classes Near Me

Anonymous said...

Excellent information providing by your post, thank you
Best HIV Treatment Hospital in India | Latest HIV Treatment in India

Pilot Industries Limited said...

Thanks for the Nice and Informative Post. Great info!
clean power for the planet

TRVDIGITAL said...

Very nice post... thanks for sharing such a nice post
Start Selling On Amazon UAE

welcome to softcrayons said...

Thanks for this amazing blog , it is very useful content for us
keep sharing this type of informtion if anyone is looking for the best training institute in nodia visit us.

Python Training Institute
data science training in noida
machine learning institute in noida
java training institute in noida
data science training in noida

Maridev said...

Experience the great learning experience with Infycle Technologies, and amazing training in AWS Training in Chennai. And we also come up with courses like Oracle, Java, Data Science, Big data, Python, Manual and Automation Testing, DevOps, Medical Coding, Power BI, Digital Marketing, etc. and we also provide excellent technical trainers with best training 100+ Live Practical Sessions with Real-Time scenarios at the end of the course the freshers, experienced, and Tech professionals will be able to obtain more knowledge of the course and be able to get through the interviews on top MNC’s with an amazing package. For more details approach us on 7504633633, 7502633633.

Scopex said...

Canli

Sonam Gangwar said...

Are you looking for a way to watch the latest Pathan movie in high-quality and for free? Look no further! Here we provide you with the best options to Pathan Full Movie Download 4K, HD, 1080p 480p, 720p in Hindi quality for free in Hindi. We have compiled a list of reliable sources that offer the highest quality streaming and downloading services. So get ready to dive into the world of Pathan with this ultimate guide on how to download it for free !

vrindha said...

Users who face the threat of IDP ALEXA 51 may not necessarily see any symptoms or signs. The virus is specifically designed by cyber frauds to avoid detection. idp.alexa.51

Ruhi said...


Nice article explaining the fundamentals of Java enums.If you want to know about python you can visit:Python training in Lucknow


Anonymous said...

Thank you for sharing! I always appreciate engaging content with valuable insights. The presented ideas are not only excellent but also captivating, making the post thoroughly enjoyable. Your continued efforts are commendable. Keep up the fantastic work.
Visit: Python in the Cloud: Deploying Apps with AWS and Azure

Priyanka Rajput said...

Thank you for sharing! I always appreciate engaging content with valuable insights. The presented ideas are not only excellent but also captivating, making the post thoroughly enjoyable. Your continued efforts are commendable. Keep up the fantastic work.

ONLEI Technologies said...

Very Nice Blog . Thanks for Posting
I found this post really interesting. This information is beneficial for those who are looking for
Python Training in Noida
Machine Learning Training in Noida
Data Science Training in Noida
Digital Marketing Training in Noida
Data Analytics Training in Noida