---
title: "How to get an enum value from a string value in Java?"  
description: "How to get an enum value from a string value in Java?"  
author: "Utpal Vishwas"  
published: 2023-07-21  
updated: 2023-07-22  
canonical: https://www.mindstick.com/forum/159227/how-to-get-an-enum-value-from-a-string-value-in-java  
category: "java"  
tags: ["java", "class", "string"]  
reading_time: 2 minutes  

---

# How to get an enum value from a string value in Java?

How to get an [enum](https://www.mindstick.com/forum/159626/how-can-i-cast-a-string-to-an-enum) value from a [string value](https://www.mindstick.com/forum/159623/how-to-get-an-enum-value-from-a-string-value-in-c-sharp) in [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming)?

## Replies

### Reply by Aryan Kumar

To get an enum [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) from a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) value in Java, you can use the valueOf() method of the enum type. The valueOf() method takes a string as a parameter and returns the enum constant that has the same name as the string.

For example, the following code gets the enum value for the string "RED":

```plaintext
enum Color {
  RED, GREEN, BLUE
}

public class Main {

  public static void main(String[] args) {
    String colorString = "RED";
    Color color = Color.valueOf(colorString);

    System.out.println(color); // RED
  }
}
```

If the string does not match any of the enum constants, the valueOf() method will throw an IllegalArgumentException.

Here is an example of how to handle an IllegalArgumentException in Java:

```plaintext
enum Color {
  RED, GREEN, BLUE
}

public class Main {

  public static void main(String[] args) {
    String colorString = "YELLOW";
    Color color;

    try {
      color = Color.valueOf(colorString);
    } catch (IllegalArgumentException e) {
      System.out.println("The color '" + colorString + "' is not a valid color.");
    }

    System.out.println(color); // null
  }
}
```

As you can see, the valueOf() method is a convenient way to get an enum value from a string value. However, it is important to handle the IllegalArgumentException that it can throw.


---

Original Source: https://www.mindstick.com/forum/159227/how-to-get-an-enum-value-from-a-string-value-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
