2

I have the following code in my presenter in a GWT MVP application:

public void onFailure(ServerFailure error) {

    String errCode = error.getMessage();

    Window.alert(errCode);
    Window.alert("Server Error: pleaseEnterQuestion");

    if(errCode == "Server Error: pleaseEnterQuestion")
        Window.alert("same");
    else
        Window.alert("different");
}

The first two alerts look exactly the same. The third alert is different. But I expect it to be same.

Alex
  • 32,506
  • 16
  • 106
  • 171
  • 2
    As a curious sidenote: in Javascript the == works fine (because it compares value). And GWT translate the String.equals to that (more or less). So this code will work in compiled mode (production mode) but not into developer mode (debug)... Said that: **please use equals!!!** :) – helios May 11 '11 at 10:32

3 Answers3

7

Use equals, not ==, to compare Strings:

if("Server Error: pleaseEnterQuestion".equals(errCode))

See this SO question for more information: How do I compare strings in Java?

Community
  • 1
  • 1
dogbane
  • 266,786
  • 75
  • 396
  • 414
2

Always use equals() when you want compare Strings. Moreover, you have to sometimes trim (left, right or just trim :)) Your String before compare, because it contains white spaces.

Samoth
  • 460
  • 1
  • 11
  • 30
1

Use .equals()

In equals the content of the string are compared not the reference ID's of the string object.

In == the objects reference ID's are compared.

The equals() method is overridden in String and Wrapper classes in java elsewhere both equals and == have same functionality.

Ankit
  • 2,753
  • 1
  • 19
  • 26