3

I am learning about enumerations and I don't understand the purpose this method serves.

Example:

enum Fruits{
    apple, pear, orange
}

class Demo{
    f = Fruits.valueOf("apple");  //returns apple... but I had to type it!
                                 // so why wouldn't I save myself some time
                                 // and just write: f = Fruits.apple; !?

}    
Sergio Gliesh
  • 329
  • 1
  • 2
  • 8
  • 4
    Maybe you received the String `"apple"` as user input and want to try to resolve it to an enum element? – JonK Jun 14 '16 at 10:29
  • One example would be a serialized text message (e.g. JSON) where one value is the representation of an enum element. In order to de-serialize an actual enum element from that, using `valueOf` would make sense. – Mena Jun 14 '16 at 10:30

2 Answers2

2

The point of valueOf method is to provide you a way of obtaining Fruits values presented to your program as Strings - for example, when values come from a configuration file or a user input:

String fruitName = input.next();
Fruits fruit = Fruits.valueOf(fruitName);

Above, the name of the fruit is provided by end-user. Your program can read and process it as an enum, without knowing which fruit would be supplied at run-time.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

I agree with @dasblinkenlight, You can use Enum.valueOf() method If you have some runtime input.

String input="apple" //It may be passed from some where
Fruits fruit = Fruits.valueOf(input);  // Here you will get the object of type Fruits

One more thing I want to add here, If the enum doesn't exist for this input, then It valueOf() method will throw a Runtime exception, instead of returning null. The exception will be:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant
pbajpai
  • 1,303
  • 1
  • 9
  • 24