Java Enum values() / valueOf() Methods

In this chapter you will learn:

  1. How to use use values() and valueOf() from enum
  2. Syntax for Enum values() and valueOf() Methods
  3. Example - Enum values() and valueOf() Methods

Description

All enumerations automatically contain two predefined methods: values() and valueOf().

Syntax

Their general forms are:


public static enum-type[ ] values() 
public static enum-type valueOf(String str)

The values() method returns an array that contains a list of the enumeration constants. The valueOf() method returns the enumeration constant whose value corresponds to the string passed in str.

Example

The following program demonstrates the values() and valueOf() methods:


enum Direction {/* w ww.  j  a  v a2  s.  com*/
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction all[] = Direction.values();
    for (Direction a : all){
      System.out.println(a);
    }
    System.out.println();

    Direction dir = Direction.valueOf("South");
    System.out.println(dir);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use enum as Class
  2. Restrictions for enum class type
  3. Example - Enum with constructor
  4. Example - Member methods
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour