I am a new programmer in Java and while programming I faced the following problem. I am trying to use switch statement on String but it gives compilation error. If any one suggest me how to use String in switch-case statement , it will be helpful to me.

Recommended Answers

All 43 Replies

You can only switch on integer constants (static final int) or literals.

you would have to covert the string to char
and you would use single quotes, example:

case 'x':

i think this kinda blows too but what are you going to do?

you would have to covert the string to char
and you would use single quotes, example:

case 'x':

i think this kinda blows too but what are you going to do?

thank u paradox.
But my purpose is not a single character. My requirement is String such as "black" "blue" etc.

like I said, you can't...
You could create a Map with those Strings as keys and integer values indexing an array of integer constants as values which you can then use as indices for the switch.
Easier to use a series of if ("black".equals(blah)) ... instead.

Was doing a research about it too. Got a simple solution, don't know if it is the best.

The String Class has a hashCode method that return the String hashcode (int) so u can do as this:

String name = "Victor";

switch (name.hashcode()) {
case "Victor".hashCode() : System.out.println("Name is Victor");
break;
case "Paul".hashCode() : System.out.println("Name is Paul");
break;
default : System.out.println("Default");
}

That MIGHT work but doesn't have to.
It all depends on the implementation of the hashcode method, which isn't guaranteed to return a unique number for each possible input.
So more than one String can yield the same hashcode.
And even if it works it's a very dirty hack.

Use enums instead.

Said that I didn't know if it was the best. Two words can really return the same hashCode, but you agree that the odds of this happening are very exceptional, don't you?

You can do too a hashCode compare of the words choosed before.

Don't understand how you are thinking about using Enum. Can you explain more ?

commented: It is clear. +0

The odds are impossible to gauge without a thorough analysis of the algorithm used.
It is however extremely easy to provide a technically correct hashCode implementation that ALWAYS returns the exact same value, so you should NEVER rely on hashCode to be even remotely unique.

As to Enums, read up on those. You can switch on them as well as on integer constants.

Took me some time to understand how to do this with enum... but still didn't get how it can help with Strings.

Example that I found.

public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}

Example using it:

public class Teste {
    public static void main(String args[]) {
        System.out.println(Operation.PLUS.eval(7,8));
        System.out.println(Operation.MINUS.eval(7,8));
        System.out.println(Operation.TIMES.eval(7,8));
        System.out.println(Operation.DIVIDE.eval(7,8));
    }
}

I repeat: You CAN'T use Strings.
So you MUST use either Enums or integer literals.

where did u find your sampl about switches on mathematical operation?

I repeat: You CAN'T use Strings.
So you MUST use either Enums or integer literals.

Well, of course you can't use Strings directly, but with the use of default enum mappings you can get nearly exactly the same thing. Looking at this:

http://www.xefer.com/2006/12/switchonstring

Enum.valueOf() is using a hash map to lookup values by the actual name of the enum, so effectively this is doing what any other language that supports switches on string is doing under the hood.

This is certainly better than using a cascade of if/else statements or ginning up a hash implementation from scratch.

Well I think what you can do is you can use string operation on your input to get such a Switch Case Statement

For Example if you want to go for Black, blue or something else.....what you can do is you make user enter string and find the alphabet position where every string has a different Char

For Example

Black
Blue
Here if you take out 3rd char and Put Switch Case statement for 3rd Char

Case 'c':
Means Input was Black

Case 'u':
Means input string was Blue...

I think it can be done in this way but I am not sure ....Can anyone tell me is it possible or not

i can help u! Just leaving m know i can assist u later. ok . fine?

Only way I know how to emulate a switch on strings, and this has already been mentioned without example code, is like the following:

void StringSwitch (String str) {
	if (str == null) { /* If the String is null... */ }
	else if (str.equals ("Some Possibility")) { /* ... */ }
	else if (str.equals ("Another Possibility")) { /* ... */ }
	else if (str.equals ("Possibility # 3")) { /* ... */ }
	// Etc, etc, etc
	else { /* DEFAULT Operation */ }
}

Keep in mind that the checks are all performed, in order, until a match is made. With large "switch" statements, the more common values should be placed near the beginning, and less common values can come near the end of the if-else statements. That'll speed up code execution, because common values won't have to be checked against dozens of not-so-common values before a match is found.

That's not a switch at all, it's just a massive if-else statement pushed into a method (not a bad idea per se) that you called "switch".

Said that I didn't know if it was the best. Two words can really return the same hashCode, but you agree that the odds of this happening are very exceptional, don't you?

You can do too a hashCode compare of the words choosed before.

Don't understand how you are thinking about using Enum. Can you explain more ?

The Fact: "even though .equals() method return false that the two objects are different...their hashcode() may not be 'neccessarily' same"...So no point of discussing in that hashcode point of view..

The Reality: if you use hashcode in SWITCH <expr> it will accept that saying..."Constant Expression Expected"..

So ENUM is best...if you really love Strings...Other best of the best...if<cond>...else if <cond>.

Thank you.

how if you input five number then the output only smallest number and the largest number will display please give the code

thank you for giving the information

you should NEVER rely on hashCode to be even remotely unique.

As to Enums, read up on those. You can switch on them as well as on integer constants.

Actually, I changed my mind. I disagree. You can rely on the hash to be unique if you know that the hash keys are fixed in advance, which in this case, you do know, because the keys are colors, and you know the set of colors that you're using in advance. In other words, you can easily test to make sure that the hash is unique. That aside, I agree with you, because it still doesn't make sense to use a hash table - what would you map to what? He's trying to decide what color a string represents. . so you're mapping colors to colors, just to use the index in a switch statement? That is unnecessary overhead and a waste of time. Similarly, the idea that someone brought up about using the enum mapping is a waste of time.

The type of the expression must be byte, char, short or int
* Case labels must be constant expressions capable of being represented by the switch expression type
* No two case constant expressions may be the same
* The default case does not have to be at the end of the code block
* If no case matches the expression, the default case will be executed
* If break is omitted between case blocks the code will fallthrough,
* continuing to execute statements until a break statement or the end of the switch block is encountered

To use enum, check the following example. It might help. But it still uses the hash value indirectly.

http://www.xefer.com/2006/12/switchonstring

ok this link has already been given. I hadn't checked all the replies.

class Switch1{ 
   public static void main(String args[]){
      int k = 10;

      switch(k){
         case 5: System.out.println(" case k = 5"); 
         break;
         case 10: System.out.println(" case k = 10"); 
         break;
         case 15: System.out.println(" case k = 15"); 
         break;
         default: System.out.println(" case default"); 
      }
   }
}

The output is case k = 10.

I haven't been in a java class for more than 3 years so I'll do this in pseudo code. This is just how I'd do it and it seems like a lot but this function could be used over and over again in many projects

int stringToInt(string1){
string string2 = "";
char char1;
for (x = 1; x < string1.length; x++){
char1 = string1.charAt(x)
switch(char1){
case 'a':
     string2 += "31";
     break;
case 'b':
     string2 += "32";
     break;
case 'c':
     string2 += "33";
     break;
case 'd':
     string2 += "34";
     break;
case 'e':
     string2 += "35";
     break;
case 'f':
     string2 += "36";
     break;
case 'g':
     string2 += "37";
     break;
case 'h':
     string2 += "38";
     break;
case 'i':
     string2 += "39";
     break;
case 'j':
     string2 += "10";
     break;
case 'k':
     string2 += "11";
     break;
case 'l':
     string2 += "12";
     break;
case 'm':
     string2 += "13";
     break;
case 'n':
     string2 += "14";
     break;
case 'o':
     string2 += "15";
     break;
case 'p':
     string2 += "16";
     break;
case 'q':
     string2 += "17";
     break;
case 'r':
     string2 += "18";
     break;
case 's':
     string2 += "19";
     break;
case 't':
     string2 += "20";
     break;
case 'u':
     string2 += "21";
     break;
case 'v':
     string2 += "22";
     break;
case 'w':
     string2 += "23";
     break;
case 'x':
     string2 += "24";
     break;
case 'y':
     string2 += "25";
     break;
case 'z':
     string2 += "26";
     break;
}
}
return(string2.parseInt());
}


switch(stringToInt("someString")){
case stringToInt("testString1"):
     ...do things...
     break;
case stringToInt("testString2"):
     ...do things...
     break;
}

a-i start with a 3 instead of a 0 because when you convert the string "01" to an int it becomes 1 I assume. You would also need to add either the capital letters or .toLower(or whatever it is in Java) depending on if you want it to be case sensitive or not.

You don't need the switch. And you cover only String with letters 'a' to 'z'. For a better approach:

String string2 = "";
char char1;
for (int x = 0; x < input.length; x++){
 char1 = input.charAt(x);
 int i = char1;
 string2 += i;
}
return string2;

Also the above might not work because you do Integer.parseInt at the end and the final String generated might be too big to be turned into an int.

I just wanted to mention an easier way to turn char variables to ints. The above approach can also be used to determine if a char is within a range of characters.

I'm guessing that pulls ascii values? I was thinking that the first ascii character would return 1 so I didn't use that but now I see it does actually return 001 so that would work.

I did think of the fact that an int can only be so long but I wasn't realizing how quickly it would come into play. With each character returning 3 number ascii values this method would break after the 4th letter in a string. This is about to get out of line and should never be done this way but now I just want to solve the problem somehow using a switch so here is my last attempt:

int stringsMatch(String str1, String str2){
     if(str1.equals(str2)){
          return 1;
     }
     return 0;
}

int int1 = 1;
switch(int1){
     case stringsMatch(str1,str2):
          ...do something...
          break;
     case stringsMatch(str1,str3):
          ...do something...
          break;
}
commented: Don't post broken code! +0

Um, please don't post stuff like that. Not only is it godawful ugly, it also defeats the purpose of a switch, and, by the way, won't even look like compiling.

Switch is a mechanism for comparing a value against a range of primitive constants, and the cases have to be primitive non-float constants. (I think even booleans are out, come to think of it) The compiler uses those values to make a lookup table, so you get a bit of a performance advantage - a function call, of course, makes that impossible.

Please try your code if you're not sure.

Reviewing this thread, it's really amazing how much bad advice there is here.
Beginners, please don't follow any of the advice given in this thread - the least bad is the chain of ifs subbed out to a method. Enums are plausible, I guess, but if you find yourself needing this sort of functionality, you really ought to ask yourself what you're doing wrong.

The cases that would call for matching a String against a number of options are very limited, and most of the ones I can think of immediately suggest doing something else entirely. Be that as it may, there aren't any really good ways to shoehorn a String into a Switch, and that's due the definition of a switch, not any deficiencies in Java.

This is about to get out of line and should never be done this way but now I just want to solve the problem somehow using a switch...

I know if defeats the purpose of a switch and I highly doubt it would compile because as I said I haven't used Java in several years and this wasn't meant to be correct syntax. I think the theory behind the code would work even if it's absolutely the wrong way to do it.

Now with everything you posted you managed to be nothing but negative and failed to give suggestions or examples for your comments. Don't take this as me being sarcastic because I'm here to learn much more than I'm here to teach.

If you find yourself needing this sort of functionality, you really ought to ask yourself what you're doing wrong.

Does this mean you can never see a situation where this would be useful? How would you handle the OP's situation? How would you handle other situations that at first glance may look like a switch on strings would be useful?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.