5

I have below code :

String s1 = "a";
    String s2 = "a";
    if (s1 == s2) {
        System.out.println("string not equal");
    }

When I analyze this code using SonarLint it doesnt get caught by it. I expect this should get caught by below Rule

squid:S1698-"==" and "!=" should not be used when "equals" is overridden

I have checked this both in standalone as well as in connected mode with Sonar Qube 7.0. Does anybody has any idea about this why sonar is behaving like this?

---------------Edit------------------

Same is also happening for :

Integer x= 500;
Integer y= 500;
if (x==y){
            System.out.println("not equal");
        }
Rips
  • 1,964
  • 1
  • 23
  • 45
  • 3
    It possibly isn't showing the warning because they're `String` literals. if you change one of them to `new String("a");` does it show the warning? – GBlodgett Apr 15 '19 at 16:07
  • actually this is correct behavior because you are using string literals and they are interned by default `intern()` and added to constant pool. so in this case == will be correct. see: https://stackoverflow.com/questions/9698260/what-makes-reference-comparison-work-for-some-strings-in-java – Nonika Apr 15 '19 at 16:08
  • @GBlodgett .If I change it to new String("a").Sonar gives me error -Constructors should not be used to instantiate "String" but still doesnt give the equals error – Rips Apr 15 '19 at 16:15
  • @Nonika -Shouldnt sonar rule squid:S1698 apply in this case ? – Rips Apr 15 '19 at 16:22
  • @Rips I have just tested the **Noncompliant Code Sample** part and the output is `they're both 'blue', they're both 'blue', they're the same object`. so it prints all the lines. there are same string objects under the hood – Nonika Apr 15 '19 at 16:29
  • @Nonika sonarkube isn't supposed to tell you if your code is correct or not. It's supposed to prevent using bad practices like comparing objects with equals(). The fact that, in this very specific case, == would lead to a correct result is irrelevant. It's still bad practice to use == to compare strings. Because, fore example, if one of the strings isn't a literal anymore in the next edition of the code, then the test will fail. – JB Nizet Apr 15 '19 at 16:35
  • @Rips have you checked the obvious, i.e. is the rule enabled? – JB Nizet Apr 15 '19 at 16:37
  • 1
    @JBNizet .Yes rule is enabled.Also I would have expected SonarLint standalone plugin to also catch such basic issue when even IntelliJ's inspector also reports it as an issue – Rips Apr 15 '19 at 17:02
  • Yes of course this is bad practice and one shouldn't ever use == to compare strings by value. – Nonika Apr 15 '19 at 17:04

0 Answers0