4

I've C code that use a lot of commands identified by static string constants.

static char* KCmdA = "commandA"
static char* KCmdB = "commandB"
static char* KCmdC = "commandC"

In C I can compare two strings with strcmp(A, B) for example but as I only refer those command via their static string identifier it's faster to only check for pointer inequality since I know my unknowCMD can only be a pointer to one of my static strings.

switch(unknowCMD)
{
    case KCmdA:
    ...
    case KCmdB:
    ...
}

I guess in Java the equivalent to strcmp would be the method equals:

unknowCMD.equals(KCmdA)

Is there an equivalent of the pointer equality in Java ? I know Java uses only references. Is it possible to use those references for equality test without actually comparing the strings ?

Sorry if this is obvious I've check the doc but did not find any definitive answer.

CodeFlakes
  • 3,671
  • 3
  • 25
  • 28

3 Answers3

6

if you compare equality of string refrences Use ==

if(str1==str2){

}
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
4

You can use ==, but it's dangerous and brittle.

Note that for Strings, the first thing equals() does is test equality of the references, so you're not buying much by doing this.

Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127
  • wow that was a fast answer. OK so equals does not actually compare the string content that's good to now. That actually make me though of a related problem. How can I use a switch statement for comparing strings ? – CodeFlakes Jul 11 '12 at 10:26
  • 2
    You need Java SE 7 for that. See http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java – mmalmeida Jul 11 '12 at 10:29
  • What ?! it's only a recent feature ? I'm developing for Android so I won't be able to use it. Anyway thanks a lot to both of you. – CodeFlakes Jul 11 '12 at 10:32
3

I think that the way you are using static strings here it would be better to use Enums. You can compare them by using .equals and ==. You can use enums in switch case too.

  • Indeed. I actually did not use them because I read somewhere that it was not recommended on Android. But it would actually probably be the best approach for my problem. I'll be able to use a switch statement with enums. – CodeFlakes Jul 11 '12 at 10:35