Is there anyway to write this piece of if statement in switch statement in Java?
Not reasonably, no, because the case
labels in Java have to be constants. (This is true of nearly all languages that have switch
, JavaScript being a rare exception.) You're probably best off with what you have, but with if/else
rather than just if
:
if (obj instanceof Integer){
// ...
}
else if (obj instanceof Double){
// ...
}
However, you can sort of do it (as of Java 7 or later), but only because of the specific classes you're testing for, which are final
and so we don't have to worry about subclasses.
switch (obj.getClass().getName()) {
case "java.lang.Integer":
// ...
break;
case "java.lang.Double":
// ...
break;
}
I do not recommend that because it does unnecessary work, and will not work correctly in the general case (e.g., if you were testing for interfaces, or classes that could be subclassed).