---
title: "How can I cast int to enum in java?"  
description: "How can I cast int to enum in java?"  
author: "Revati S Misra"  
published: 2023-08-21  
updated: 2023-08-23  
canonical: https://www.mindstick.com/forum/159628/how-can-i-cast-int-to-enum-in-java  
category: "java"  
tags: ["java", "enum"]  
reading_time: 2 minutes  

---

# How can I cast int to enum in java?

How can I [cast int to enum](https://www.mindstick.com/forum/159564/how-do-i-cast-int-to-enum-in-c-sharp) in C#?

## Replies

### Reply by Aryan Kumar

Sure, here are two ways to [cast](https://answers.mindstick.com/qa/97273/how-to-cast-a-baitcaster) [int](https://www.mindstick.com/forum/159137/how-to-convert-date-int-to-date-in-sql) to [enum](https://www.mindstick.com/forum/159626/how-can-i-cast-a-string-to-an-enum) in Java:

1. Using the `.valueOf()` method:

Java

```plaintext
enum MyEnum {
  VALUE1,
  VALUE2,
  VALUE3
}

int myInt = 1;

// Cast the int to an enum using the valueOf() method.
MyEnum myEnum = MyEnum.valueOf(myInt);
```

In this example, the `myInt` variable is an int that has the value 1. The `myEnum` variable is an enum that is initialized to the value of `VALUE1`. The `MyEnum.valueOf(myInt)` method casts the `myInt` variable to an enum.

1. Using the `instanceof` operator:

Java

```plaintext
enum MyEnum {
  VALUE1,
  VALUE2,
  VALUE3
}

int myInt = 1;

// Check if the int is an instance of the enum.
if (MyEnum.class.isInstance(myInt)) {
  // Cast the int to an enum.
  MyEnum myEnum = (MyEnum) myInt;
}
```

In this example, the `myInt` variable is an int that has the value 1. The `MyEnum.class.isInstance(myInt)` method checks if the `myInt` variable is an instance of the `MyEnum` enum. If it is, then the `myEnum` variable is casted to an enum.

Which method you use depends on your specific needs. If you need to cast an int to an enum and you don't need to do any further processing on the enum value, then the `valueOf()` method is a good option. If you need to do further processing on the enum value, then the `instanceof` operator is a good option.


---

Original Source: https://www.mindstick.com/forum/159628/how-can-i-cast-int-to-enum-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
