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

Answer

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.

Attribution
Source : Link , Question Author : Andrii Muzychuk , Answer Author : Rao

Leave a Comment