Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell Eclipse to warn me when I compare Strings with == instead of .equals()

Tags:

java

eclipse

People also ask

Can you use == when comparing strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

What happens when you compare two strings with the == operator?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

Can you use == for strings in Java?

== operator compares the reference of an object in Java. You can use string's equals method .

Can two strings be compared using == in Java?

We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.


https://bugs.eclipse.org/bugs/show_bug.cgi?id=39095

Bug 39095 - RFE: warn when non-primitives are compared using ==

It would be nice if the compiler could allow warning when == is used to compare non-primitive types, so that String's compared with ==, while a valid approach if you're intern'ing and using the string pool, can be caught as compile-time warnings instead of run-time non-obvious breakages..


Eclipse can never tell you that. Findbugs or PMD probably can.

EDIT : I say

Eclipse can never tell you that.

because there nothing wrong with code a == b as java code. If you want some extra help, this is where other plugins come to help.

Edit: According to Pascal Thivent, Findbugs can't do this, but it looks like PMD can. I'm leaving the link to Findbugs, though, since it's probably a useful link for people who come across this question.