Search code examples
javaenumerationvalue-of

What is the point of the static valueOf() method? (enumerations)


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; !?

}    

Solution

  • 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.