Link to home
Start Free TrialLog in
Avatar of saedpalnet
saedpalnet

asked on

switch statement on a java string

Hi,
is there away to do java switch statment on a string variable? I know it can be done on integer but not strings. any work around if I need to do a switch case statements on a string variable in java?

Thanks
Avatar of wolfc
wolfc

Nope.
you can use switch on int char and other primitive type.
String is not a primitive type, but Object type.

Bye, Giant.
Hehe, the workaround:

if(str.equals("A")) {
  ..
}
else if(str.equals("B")) {
  ..
}

The funny workaround (don't use this one):

switch(str.hashCode())
{
  case 0x01234567:
    ..
    break;
  case 0x89abcdef:
    ..
    break;
}

It will give you a switch in the code, but it won't work reliable.
In particular switch could be used with:
char, byte, short, int.
Avatar of girionis
If it is a one char string you coudl convert it to char and do it, otherwise there is no way as staed above.
Avatar of saedpalnet

ASKER

I cant believe java is weak at this... one can easily do this in other languages like PHP for example!!
its hard to convince my manager who knows something about programming that one cant do a switch case on a string in java !!:)
I tried the .hashCode solution long time ago but thought it looks ugly with bad results too!
SOLUTION
Avatar of Giant2
Giant2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Map strings to constant varibales of int type with names similar as Strings  and use reflection to get them.

i.e. If you want to switch for
String s = "HELLO";
String s1 = "HELLO2";

create an integer like

const int HELLO=1;
const int HELLO2=2;

and so on

Then use the reflection to get the names of the variables according to the strings and use switch on them

:)
>> its hard to convince my manager who knows something about programming that one cant do a switch case on a string in java !!:)
Be glad you have one *who knows something about programming*. Most of them don't. ;°)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And a switch is just a glorified if/else anyways
>> Then use the reflection
Think then you can better use a map to make the link between the Strings and the ints:

private final String STR_HELLO = "Hello";
private final String STR_WORLD = "World";
...

private final int INT_HELLO=1;
private final int INT_WORLD=2;
...

Map theMap = new HashMap();
theMap.put( STR_HELLO, new Integer(INT_HELLO) );
theMap.put( STR_WORLD, new Integer(INT_WORLD) );
...

String theString = .....;
int value = theMap.contains(theString) ? ((Integer)theMap.get(theString)).intValue() : -1;
switch (value) {
   case INT_HELLO:
       break;
   case INT_WORLD:
       break;
   default:
       break;
}
>And a switch is just a glorified if/else anyways
Full agree, as I posted before.
> Think then you can better use a map to make the link between the Strings and the ints:

though far simpler to just use an if/then/else
> its hard to convince my manager who knows something about programming that one cant do a switch case on a string in java

ask him under what situation you would need a switch, that could not be handled by an if/then/else statement
:)
ok guys...
thanks alot for you comments... I think I got the answer I want. I wanted mainly to be sure and find a more elegant way of doing the coding. I have to split the points, which is not much anyways, I hope I did it right ... thanks to you all  armoghan, girionis, wolfc, Giant2 and zzynx :)
Regards
You could do something on these lines, but you'd have to watch for duplicate strings.


  String st = "Hello";

  byte[] b = st.getBytes();
  int[] intt = new int[b.length];
  int sum=0;

  for(int a=0;a<b.length;a++){sum+=(int)b[a];}

  System.out.println(sum);

   switch (sum){

     case (100):{}

  }
and objects for sure :)
thank you krakatoa, but I think I will just stick with the original if else solution!
> and objects for sure :)

;)
>> thanks alot for you comments...
Thanks for accepting.

>> I think I got the answer I want
Just wondering, any reason why grading with a C?
sorry about that, I think it was done by mistake... is there away I can change it?
Nice to hear we were of help :)
>> it was done by mistake
To know that is OK for me.

>> is there away I can change it?
If you would like, yes.
Post a zero-point question in https://www.experts-exchange.com/Community_Support/ asking for reopening it.

Subject: Please Reopen
Body: Please reopen this question:
          https://www.experts-exchange.com/questions/21081620/switch-statement-on-a-java-string.html

After is has been reopened by a moderator, you can reaccept.

Bear in mind that people reading this thread afterwards expect the comment marked as "Accepted answer" as "the answer" to the question.
So, better mark one of the workarounds as accepted answer.
(PS: That's completely apart from the points you give each comment. That's even invisible)
Can I be part of the split this time ;)
Thanks again :°)
thanks.
>> Can I be part of the split this time ;)

:D !
Couldn't you do a switch on the hashCode()?  I realize you might get a falsePositive match, but it's highly unlikely.


String s = "EDIT";
final int INT_ADD = "ADD".hashCode();
final int INT_EDIT = "EDIT".hashCode();
final int INT_DELETE = "DELETE".hashCode();

switch (s.toUpperCase().hashCode()) {
   case INT_ADD:
       //do ADD process
       break;
   case INT_EDIT:
       //do EDIT process
       break;
   case INT_DELETE:
       //do DELETE process
       break;
   default:
       break;
}
Sorry, but I have to add some Java 1.5 code here, just to show a different method of doing it without integers and such.


package nl.warper.test;
 
public class SwichByEnumDemo {
	static enum NumeralEnum {
		ONE, TWO;
	}
	
	public static void main(final String[] args) {
		final NumeralEnum numeral; 
		try {
			numeral = NumeralEnum.valueOf(args[0].toUpperCase());
		} catch(IllegalArgumentException e) {
			throw new RuntimeException("String has no matching NumeralEnum value");
		}
		switch(numeral) {
		case ONE:
			System.out.println("The string had value ONE!");
			break;
		case TWO:
			System.out.println("The string had value TWO!");
			break;
		default:
			System.out.println("NumeralEnum has an additional value that has not been handled in a switch statement");
			break;
		}
	}
}

Open in new window