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

Viewed 4015

I know that when comparing Strings, you should use .equals() not == and I understand the reasons for this. However I do sometimes forget and compare strings with == by mistake. I would like it if Eclipse (being much smarter than me), would warn me by doing one or more of the following:

  • Underlining my mistake with a wiggly red line and pointing out the mistake
  • Refusing to compile my code until I fix the mistake
  • Fixing the mistake for me
  • Beating me over the head with the nearest Joshua Bloch book until I apologize

In Eclipse 3.5, you can have Eclipse warn you about all kinds of things, by going to Window > Preferences > Compiler > Errors/Warnings, but sadly "Comparing strings with == instead of .equals()" does not seem to be one of them. Am I just missing it? Is there any chance of adding this in a future release?

EDIT: I'd rather do this using Eclipse's built-in functionality, rather than have to download a plugin. However, I think it would still be useful to mention plugins that have this feature in your answers.

4 Answers

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.

I dont think you can.

Using == is a valid java language feature. There would be circumstances where you would want to do this exact thing. Then what?

Probably, one fine day some programmer would want the IDE to warn him when he writes i = 10 (instead of i == 10)

Fortunately, this is where the human takes over the machine and we all have our jobs :)

Sadly, there are so many buggy systems :(

I am sure, over time you will get in the habit of using equals() for String

Related