Is there any difference in equals and == for String variables?

  • if ('text'.equals(str))
    

    or

    if ('text' == str)
    

    Is there any difference? If yes, then what is it?



    Added, after answered.

    String q = 'teXt';
    system.debug('teXt'.equals(q)); // true
    system.debug('teXt' == q);      // true
    system.debug('text'.equals(q)); // false
    system.debug('text' == q);      // true
    
  • Rao

    Rao Correct answer

    6 years ago

    Yes there is a major difference, Case sensitivity.

    https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm

    > equals(stringOrId) Returns true if the passed-in object is not null and represents the same binary sequence of characters as the current string. Use this method to compare a string to an object that represents a string or an ID.

    == is same as equalsIgnoreCase(secondString)

    Returns true if the secondString is not null and represents the same sequence of characters as the String that called the method, ignoring case.

    Hi, is there any doc that says that "== is the same as equalsIgnoreCase"? If so, please add it to your post. Cheers

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used