2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
It's almost always a mistake to compare two instances of ``++java.lang.String++`` or boxed types like ``++java.lang.Integer++`` using reference equality ``++==++`` or ``++!=++``, because it is not comparing actual value but locations in memory.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();
if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
String firstName = getFirstName();
String lastName = getLastName();
if (firstName != null && firstName.equals(lastName)) { ... };
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/595[CWE-595 - Comparison of Object References Instead of Object Contents]
* CWE - https://cwe.mitre.org/data/definitions/597[CWE-597 - Use of Wrong Operator in String Comparison]
2021-04-28 16:49:39 +02:00
* https://wiki.sei.cmu.edu/confluence/x/UjdGBQ[CERT, EXP03-J.] - Do not use the equality operators when comparing values of boxed primitives
* https://wiki.sei.cmu.edu/confluence/x/yDdGBQ[CERT, EXP50-J.] - Do not confuse abstract object equality with reference equality
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== relates to: S1698
=== on 31 Oct 2018, 17:41:57 Tibor Blenessy wrote:
RSPEC-1698 has to exclude ``++java.lang.String++`` and boxed types to not raise duplicate issues
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]