0

Possible Duplicate:
How do I compare strings in Java?

I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:

    String myString = "s";
    char myChar = 's';//both string and char are assigned as letter 's'

    String stringFromChar = String.valueOf(myChar);

    if (myString == stringFromChar) {
        out.println("equal");
    } else {
        out.println("not equal");
    }

Every time it prints not equal. Please help, thanks! :)

Community
  • 1
  • 1
Arch1tect
  • 4,128
  • 10
  • 48
  • 69
  • 3
    Read [How do I compare strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo Jan 15 '13 at 01:44

3 Answers3

6

== compare the reference, not the actual value. You must use equals to compare the value.

Read this article if you don't understand it's clear and simple.

Jean-Philippe Bond
  • 10,089
  • 3
  • 34
  • 60
3

NEVER DO THIS AGAIN!!! PROMISE ME!!! =P

When comparing strings always, always, always use the equals method. See Below!

    String myString = "s";
    char myChar = 's';//both string and char are assigned as letter 's'

    String stringFromChar = String.valueOf(myChar);

    if (myString.equals(stringFromChar)) {
        System.out.println("equal");
    } else {
        System.out.println("not equal");
    }
}
SpiffyDeveloper
  • 127
  • 1
  • 7
1

what happens when converting char to string?

Well, you are using the String.valueOf(char) method, whose javadoc does not say how it does the conversion. But the behaviour you are seeing strongly suggests that the JVM you are using creates a new String object each time you call the method.

But you should depend on this happening.

The bottom line is that you should always use the equals method to compare strings. Comparing strings with == will often give you false negatives ... depending on how the strings were created / obtained. You've just been bitten by that. Learn.

Reference:

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216