Solved

switch statement on a java string

Posted on 2004-08-04
33
69,500 Views
Last Modified: 2011-08-18
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
0
Comment
Question by:saedpalnet
  • 6
  • 6
  • 5
  • +7
33 Comments
 
LVL 1

Expert Comment

by:wolfc
ID: 11713106
Nope.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11713119
you can use switch on int char and other primitive type.
String is not a primitive type, but Object type.

Bye, Giant.
0
 
LVL 1

Expert Comment

by:wolfc
ID: 11713132
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.
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 12

Expert Comment

by:Giant2
ID: 11713136
In particular switch could be used with:
char, byte, short, int.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11713137
If it is a one char string you coudl convert it to char and do it, otherwise there is no way as staed above.
0
 

Author Comment

by:saedpalnet
ID: 11713176
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!
0
 
LVL 12

Assisted Solution

by:Giant2
Giant2 earned 30 total points
ID: 11713184
you can use a "simulated" switch statement:
if
else if
else if
else if
...

but I believe it's not really elegant.
0
 
LVL 37

Accepted Solution

by:
zzynx earned 55 total points
ID: 11713200
>> is there away to do java switch statment on a string variable?
>> I know it can be done on integer but not strings.
Nice to answer your Q yourself. ;°)

>> any work around
First, what's wrong with the if/else if pair?

But if you really want one:

If you don't have too much strings you know beforehand,
you could make a unique link between the string and an integer by using a list:

List theList = new ArrayList();
theList.add("StringAtIndex0");
theList.add("StringAtIndex1");
theList.add("StringAtIndex2");
theList.add("StringAtIndex3");
...

String theString = "StringAtIndex2";
int index = theList.indexOf(theString);
switch(index) {
   case 0: // means StringAtIndex0

      break;

   case 1: // means StringAtIndex1

      break;

   case 2: // means StringAtIndex2

      break;

   case 3: // means StringAtIndex3

      break;

   default :
      break;
}
0
 
LVL 18

Expert Comment

by:armoghan
ID: 11713221
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

:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11713225
>> 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. ;°)
0
 
LVL 1

Assisted Solution

by:wolfc
wolfc earned 40 total points
ID: 11713247
If you need to convince your manager:

Suppose a switch with an Object is possible would the case statements be equal when the reference is equal or when the content is equal?
If the reference should be equal the switch is useless. If the content should be equal which method should be used for that evaluation?
Either by implying the use of equals() (loosened semantics) or by allowing operator overloading.
PHP has loosened semantics, which leads to a kind of fuzzy logic in the code (the string is equal enough for me).
C++ has operator overloading, which leads to unreadable code (maybe == is properly overloaded, maybe not).

I like the Java solution, clear semantics, no operator overloading, can't switch on an Object.
0
 
LVL 92

Expert Comment

by:objects
ID: 11713265
And a switch is just a glorified if/else anyways
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11713284
>> 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;
}
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11713300
>And a switch is just a glorified if/else anyways
Full agree, as I posted before.
0
 
LVL 92

Expert Comment

by:objects
ID: 11713306
> 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
0
 
LVL 92

Expert Comment

by:objects
ID: 11713323
> 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
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11713377
:)
0
 

Author Comment

by:saedpalnet
ID: 11713387
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
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 11713400
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):{}

  }
0
 

Author Comment

by:saedpalnet
ID: 11713401
and objects for sure :)
0
 

Author Comment

by:saedpalnet
ID: 11713417
thank you krakatoa, but I think I will just stick with the original if else solution!
0
 
LVL 92

Expert Comment

by:objects
ID: 11713419
> and objects for sure :)

;)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11713437
>> 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?
0
 

Author Comment

by:saedpalnet
ID: 11713461
sorry about that, I think it was done by mistake... is there away I can change it?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11713488
Nice to hear we were of help :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11713544
>> 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 http://www.experts-exchange.com/Community_Support/ asking for reopening it.

Subject: Please Reopen
Body: Please reopen this question:
          http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21081620.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)
0
 
LVL 92

Expert Comment

by:objects
ID: 11722354
Can I be part of the split this time ;)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11723717
Thanks again :°)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11723778
thanks.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 11724044
>> Can I be part of the split this time ;)

:D !
0
 

Expert Comment

by:snekse
ID: 13106517
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;
}
0
 
LVL 9

Expert Comment

by:mbodewes
ID: 21242502
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

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Weekend adv creator 3 38
expectj telnet failing 5 36
hibernate example using maven 12 42
Tomcat: Unable to run tomcat service. 2 20
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question