views:

145

answers:

3

I am completely stumped with this one . . .

If I call the function below with the following:

Search(SearchTextField.getText()); // (Fiberglass was entered)

Search("Fiberglass"); // hardcoded

I get the following results:

Fiberglass 10 Not Here

Fiberglass 10 String found!

Same String is passed with the same length, different results. How can this be? Yes I've trimmed it on both sides of the == with no luck.

I am loosing my mind, any help would be appreciated.

Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);




    public void Search(String searchString) {

    boolean found = false;
    System.out.print(searchString + " " + searchString.length() + " ");

    for (int i = 0; i < array.length; i++) {

        if (searchString == array[i].getBoatMaterial()) {
            found = true;
            break;
        }
    }
    if (found) {
        System.out.println("String found!");
    } else {
        System.out.println("Not Here");
    }
}
+4  A: 

Use the .equals() method when you're comparing Strings. Do not use ==

equals() will compare the actual String content, no matter where the String resides in memory.

if (searchString.equals(array[i].getBoatMaterial())) {
Matt
Matt, thank you a million times. Works like a charm.
JS
+4  A: 

Since String variables are references in Java, when you code

    if (searchString == array[i].getBoatMaterial()) {

What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.

Jim Garrison
Jim, if I could give you some credit I would. Excellent explanation completely makes sense now.Thanks
JS
You could upvote the answer :-)
Jim Garrison
Answer Upvoted!
JS
+3  A: 

Use the String.equals(String other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.

Summy