| Subcribe via RSS

Java Enum example

July 10th, 2009 Posted in Java

This post will show you how to work with the enumerations in Java, is pretty easy to use and it can be really useful once you get to know it. You will see in the example a basic use that will put you in the right direction so you can implement your own Enums in the future.The Enums in java are basically used to name a certain list of elements that you want to use , the enums are very flexible and easy to use in Java, and here you can see a simple but good example of how to handle the enums in java, and the things you can do with it.

In the example I’m going to define an Enum in Java and just print the values , so you can see it.

/*
 * Basic example about Enumeration in Java
 *
 */

/**
 *
 * @author neozilon
 */
public class EnumerationExample {

    public enum Cars{
        MERCEDES(1),
        MITSUBISHI(1),
        MAZDA(3),
        TOYOTA(4),
        FERRARI(5);

        private final int id;

        Cars(int id) { this.id = id;}

        public int getValue() { return id; }
    }

    /**
     * prints all Car items and its values
     */
    public void printCarsValues(){

        Cars[] carsArray = Cars.values();
        for (int i=0; i < carsArray.length; i++){
            Cars item = carsArray[i];
            System.out.print(" CAR: " + item.name() );
            System.out.println(" VALUE: " + item.getValue());
        }
    }

    /**
     * shows how to access any item in the enumeration
     */
    public void printOneCar(){

        System.out.println(" ------- \n print just one item \n ");
        System.out.println("Car: " + Cars.MAZDA + " Value: " + Cars.MAZDA.getValue());
    }

    public static void main(String[] args){

        // enum test values
        EnumerationExample example = new EnumerationExample();

        // print all the items
        example.printCarsValues();

        // print just one item
        example.printOneCar();
    }

}

and here is the output that you will get , if you run this class:

run:
 CAR: MERCEDES VALUE: 1
 CAR: MITSUBISHI VALUE: 1
 CAR: MAZDA VALUE: 3
 CAR: TOYOTA VALUE: 4
 CAR: FERRARI VALUE: 5
 -------
 print just one item 

 Car: MAZDA Value: 3

As you can see, is really easy to use enums in java, and can be very powerful if you want, and save you a lot of time.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Furl
  • Slashdot
  • Technorati
  • TwitThis

2 Responses to “Java Enum example”

  1. dewani Says:

    Hey, I am noob at geek stuff. This helped me in my project. Thank you


  2. Anonymous Says:

    One of the most natural example of enum. enums are good choice to represent fixed set of input and your program shows that but at same time enum could be lot more dynamic and flexible here is an example of java enum which shows that.


Leave a Reply