How do I cast an object as int in Java?

Asked 2 years ago, Updated 2 years ago, 163 views

I want to cast an object as int. How do I do it

casting object java integer

2022-09-22 22:14

1 Answers

If the value of the object is Integer, int i = (Integer)object; You can do it.

If you have Java 7 or higher, int i = (int) object; You can do it.

However, if Object is not integer, a ClassCastException error may occur. Also, if the object is null, NullPointerException will occur. So you can use it when it's definitely an integer, not a null.

If the value of the object is String, use Integer.valueOf(). int i = Integer.valueOf((String) object); You can write it like this. However, if String is not in Integer format, NumberFormatException will occur.


2022-09-22 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.