Solved

switch statement on a java string

Posted on 2004-08-04
33
69,476 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
Comment Utility
Nope.
0
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
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
Comment Utility
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
 
LVL 12

Expert Comment

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

Expert Comment

by:girionis
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
And a switch is just a glorified if/else anyways
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> 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
Comment Utility
>And a switch is just a glorified if/else anyways
Full agree, as I posted before.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> 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
Comment Utility
> 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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 12

Expert Comment

by:Giant2
Comment Utility
:)
0
 

Author Comment

by:saedpalnet
Comment Utility
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
Comment Utility
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
Comment Utility
and objects for sure :)
0
 

Author Comment

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

Expert Comment

by:objects
Comment Utility
> and objects for sure :)

;)
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> 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
Comment Utility
sorry about that, I think it was done by mistake... is there away I can change it?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Nice to hear we were of help :)
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> 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
Comment Utility
Can I be part of the split this time ;)
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
Thanks again :°)
0
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
thanks.
0
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
>> Can I be part of the split this time ;)

:D !
0
 

Expert Comment

by:snekse
Comment Utility
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
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now