Sergio Gliesh Sergio Gliesh - 1 year ago 71
Java Question

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.


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


Answer Source

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 =;
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download