Sergio Gliesh Sergio Gliesh - 4 months ago 7
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 =; !?



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.