2021-04-28 16:49:39 +02:00
|
|
|
It is preferable to place string literals on the left-hand side of an ``++equals()++`` or ``++equalsIgnoreCase()++`` method call.
|
|
|
|
|
|
|
|
This prevents null pointer exceptions from being raised, as a string literal can never be null by definition.
|
|
|
|
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2021-04-28 16:49:39 +02:00
|
|
|
== Noncompliant Code Example
|
|
|
|
|
|
|
|
----
|
|
|
|
String myString = null;
|
|
|
|
|
|
|
|
System.out.println("Equal? " + myString.equals("foo")); // Noncompliant; will raise a NPE
|
|
|
|
System.out.println("Equal? " + (myString != null && myString.equals("foo"))); // Noncompliant; null check could be removed
|
|
|
|
----
|
|
|
|
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2021-04-28 16:49:39 +02:00
|
|
|
== Compliant Solution
|
|
|
|
|
|
|
|
----
|
|
|
|
System.out.println("Equal?" + "foo".equals(myString)); // properly deals with the null case
|
|
|
|
----
|
2021-04-28 18:08:03 +02:00
|
|
|
|
|
|
|
|
2021-06-02 20:44:38 +02:00
|
|
|
|
|
|
|
ifdef::rspecator-view[]
|
|
|
|
== Comments And Links
|
|
|
|
(visible only on this page)
|
|
|
|
|
|
|
|
include::comments-and-links.adoc[]
|
|
|
|
endif::rspecator-view[]
|