Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal expressions should be on the left side of an equals comparison

!mapData.get("PARTY_ID").equals("")         // <-- gives SonarQube error

In the above piece of code, I am getting "String literal expressions should be on the left side of an equals comparison" this error in Sonar. So how we can avoid it.

I tried this:

("").equals(!mapData.get("CON_PTY_PARTY_ID"))

But it does not work. Give some advice......

like image 452
Wolverine789 Avatar asked Jul 09 '14 14:07

Wolverine789


People also ask

What is literal in string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

Do you use == or .equals for string?

Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.

Can you compare string literals in C?

In C, you can compare single characters (chars) by using the comparion operator ==, however, this method is not valid for comparing arrays of chars, or strings. Instead, you must use a function that compares each of the chars within the arrays in turn.

How do you check if a string is a literal?

Now how we will check whether the string is a literal or an object. For this, we will be using the typeof operator. The typeof operator returns the type of any data type in JavaScript and returns their actual data type. Operands can either be literals or data structures such as variables, functions, or objects.


2 Answers

Others have pointed out that the way to avoid this error is to use:

! ("".equals(mapData.get("CON_PTY_PARTY_ID")))

But no one has pointed out why this matters. The reason the literal should be on the left side of the equals comparison is to avoid the possibility of an exception if the string being compared to it is null.

As written in the question, if the value of mapData.get("CON_PTY_PARTY_ID") was null, then the expression would be trying to invoke the equals(..) method of an object that doesn't exist. That would throw an exception. By putting the literal on the left, then even if the value of mapData.get("CON_PTY_PARTY_ID") was null, the method "".equals(...) would be defined and would not throw an exception. It would simply return false.

like image 74
Mark Meuer Avatar answered Sep 25 '22 14:09

Mark Meuer


You shouldn't surround a blank string with quotes. ("").equals(!mapData.get("CON_PTY_PARTY_ID")) should just be ! ("".equals(mapData.get("CON_PTY_PARTY_ID")))

like image 34
Kevin W. Avatar answered Sep 22 '22 14:09

Kevin W.