Convert object to int in Java
Description
The following code shows how to convert object to int.
Example
/*w w w . j a v a 2 s. co m*/
public class Main {
public static int toInt(Object object, int defaultValue) {
if (object == null) {
return defaultValue;
}
else if (object instanceof Number) {
return ((Number) object).intValue();
}
else if (object instanceof String) {
try {
return Integer.parseInt((String) object);
}
catch (NumberFormatException ex) {
return defaultValue;
}
}
return defaultValue;
}
public static void main(String[] argv){
System.out.println(toInt('1',0));
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »