Error when comparing to strings


Last Updated:

  1. tellblom

    tellblom New Member This Topic's Starter

    Joined:
    Jun 29, 2010
    Messages:
    2
    Likes Received:
    0
    I have this code in my app

    Ver = "1.5.2"
    VersionsKoll = "1.5.2"

    if (VersionsKoll == Ver)
    {
    //Do something
    }​

    This gets the result "false"​

    When I debug I get this in the watchwindow:
    http://www.tellblom.se/android/strings.jpg

    Can someone explain this to me?
    /M​
     

    Advertisement
  2. markb

    markb Well-Known Member

    Joined:
    Sep 14, 2009
    Messages:
    148
    Likes Received:
    26
    Hi tellblom,

    Your code is behaving correctly as Ver and VersionsKoll are different objects, and == tests to see if two variables refer to the same object. It doesn't check if the two objects have the same value. In C/C++ terms it's like comparing two pointers to see if they have the same address, rather than checking to see if they point to data that looks the same.

    To compare strings you need to use the "equals" method on one of the strings.

    Code (Text):
    1. if ( VersionKoll.equals(Ver) )
    2. {
    3.  . . . they match . . .
    4. }
    5.  
    In general, if the string could be null, then you'd write something like this instead, so you don't call a method on a null object:

    Code (Text):
    1. if ( VersionKoll != null && VersionKoll.equals(Ver) )
    2. {
    3.  . . . they match . . .
    4. }
    5.  
    See this page for more information:

    Comparing Strings and Portions of Strings (The Java
     
    tellblom likes this.
  3. tellblom

    tellblom New Member This Topic's Starter

    Joined:
    Jun 29, 2010
    Messages:
    2
    Likes Received:
    0
    Thanx alot,

    As you proberbly understand I usually code in C# and the quite similar to java.

    Once again thanx for this.

    /M
     

Share This Page

Loading...