954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

switch statement on String in Java

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.

niamul
Newbie Poster
12 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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?

paradox814
Posting Whiz
351 posts since Oct 2004
Reputation Points: 13
Solved Threads: 4
 

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.

niamul
Newbie Poster
12 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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");
}

cyberowl
Newbie Poster
3 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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 ?

cyberowl
Newbie Poster
3 posts since Dec 2006
Reputation Points: 10
Solved Threads: 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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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));
}
}

cyberowl
Newbie Poster
3 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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

rLh
Newbie Poster
2 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 
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.

Ficke
Newbie Poster
1 post since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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

staneja
Junior Poster in Training
64 posts since Dec 2006
Reputation Points: 10
Solved Threads: 2
 

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

manojdesai
Newbie Poster
3 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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.

Cudmore
Junior Poster in Training
74 posts since Nov 2005
Reputation Points: 20
Solved Threads: 6
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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 it will accept that saying..."Constant Expression Expected"..

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

Thank you.

nnprasad2000
Newbie Poster
8 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
 

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

Boyett Martinet
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

thank you for giving the information

Boyett Martinet
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You