-4

Is there anyway to write this piece of if statement in switch statement in Java?

Object obj;
if (obj instanceof Integer){

}

if (obj instanceof Double){

}

....

This is just an example. Integer of Double could be replaced by any other object types

Trung Bún
  • 1,117
  • 5
  • 22
  • 47
  • Could you provide an example please? Many thanks! – Trung Bún Mar 08 '15 at 18:56
  • 2
    @manouti But that is not the same as `instanceof` which is polymorphic. – RealSkeptic Mar 08 '15 at 18:56
  • @RealSkeptic You're right. BTW, [this question](http://stackoverflow.com/questions/5579309/switch-instanceof) may help. – M A Mar 08 '15 at 18:58
  • 1
    OP: Usually, a chain of `instanceof` conditions is an indication of bad class design. Perhaps you should tell us why you need this so we can suggest a change in the design. – RealSkeptic Mar 08 '15 at 18:59
  • I think this question has been previously answered: http://stackoverflow.com/questions/5579309/switch-instanceof – Dkarode Mar 08 '15 at 18:59

2 Answers2

2

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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No. You see, switch statements are for comparing many different values of the same type for a match to a certain other value.

A switch statement is formed like this:

switch (var){
    case 5:
    //var == 5
    break;
    case 10:
    //var == 10
    break;
    default:
    //var is not 5 nor 10
    break;
}

Which only allows comparisons to constant values, thus making it useless towards data types. An if statement is a much better choice for this purpose, as the only solution for using a switch statement (getting the instance name and comparing it in that format) would be writing too much extra (and unnecessary) code that is not needed and can more easily be done in another manner.

DripDrop
  • 994
  • 1
  • 9
  • 18