This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

Bug 236156 - Incorrect "Comparing string using ==" hint when using constants
Summary: Incorrect "Comparing string using ==" hint when using constants
Status: NEW
Alias: None
Product: java
Classification: Unclassified
Component: Hints (show other bugs)
Version: 7.3.1
Hardware: PC Linux
: P3 normal (vote)
Assignee: Svata Dedic
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-09-19 15:59 UTC by dusty
Modified: 2015-10-02 16:41 UTC (History)
0 users

See Also:
Issue Type: ENHANCEMENT
Exception Reporter:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description dusty 2013-09-19 15:59:35 UTC
Hello,
if I have a piece of code similar to this one:

public final static String STR1="dummy";
...
String s = STR1;
if (s == STR1) {
...
}

in the "if" line the editor gives me the hint reported on the subject, but in this special case the comparison is correct (at least, I think so).

I understand it's a bit tricky to deduce that when a String is only assigned by constants the comparison can be made with == and !=, but it's a bit annoying to have warnings in the code when the there is no problem, so I report it as an enhancement.
Comment 1 Svata Dedic 2013-10-01 16:32:32 UTC
Comparison using == can be dangerous even in your case; each String compile time constant is implicitly interned. As a result, if there's a piece of code, which happens to call x = v.intern() on String v containing "dummy", STR1 and x will receive the same reference and the comparison in your example might evaluate to true inappropriately.

In case you *want* to have String constant and compare by reference, use explicit new String("dummy") to work around the implicit intern.

This enhancement would probably require a NB specific source-only annotation on the declared element; other possibility would be to @SuppressWarnings() for the unwanted hint code - should be one of the options offered in hints.
Comment 2 dusty 2013-10-01 19:32:59 UTC
Thanks for the insight.

I don't know much about string interning: am I right to say that anyway, if the content of the string is different, it's not possible to have v == s?

In understand that using two different constants with the same value is certainly a good way to look for problems :)
Comment 3 Svata Dedic 2015-10-02 16:41:26 UTC
The hint could look out for @SuppressWarnings on the constant. Placing specific @SuppressWarning on a constant would also declare that the programmer intents to work with the exact instance rather than with value.