How to cast an Object to an int
To cast an Object
to an int
in Java, you can use the intValue()
method of the Integer
class.
Here's an example of how you can cast an Object
to an int
:
public class Main {
public static void main(String[] args) {
Object obj = 5; // obj is an Integer object
// Cast obj to an int using the intValue() method
int x = ((Integer) obj).intValue();
System.out.println(x); // prints 5
}
}
In this example, the obj
variable is an Object
that contains an Integer
object with the value 5
. The intValue()
method is used to cast the Integer
object to an int
and assign it to the x
variable.
I hope this helps! Let me know if you have any questions.