Menu

#976 UselessStringValueOf wrong when appending character arrays

PMD-5.0.3
closed
pmd (543)
PMD
3-Major
Bug
2013-04-05
2011-08-19
No

PMD reports UselessStringValueOf as warning when concatenating a String with a character array. I think the warning is wrong in this case and can lead to bugs when the warning is fixed.

Please see the folloing code snipped:

char[] idFormat = {'0', '0', '0', '0', '0'};
String abc = "1" + String.valueOf(idFormat); // PMD reports a warning here
System.out.println(abc); // Output 100000

So, we fixed the code based on the PMD warning to this:

char[] idFormat = {'0', '0', '0', '0', '0'};
String abc2 = "1" + idFormat; // No warning!
System.out.println(abc2); // Outputs: 1[C@1f8b5b

The reason is that char[].toString() is not equal to String.valueOf(char[]). I think that the UselessStringValueOf rule should not report a warning in this case.

Discussion

  • Steven Christou

    Steven Christou - 2011-08-21

    I agree this could be an issue. The addition operator on a [] would point to object references and not content value, and in this instance it will produce a false positive. Can you assign to me to fix? If not I will fix.

     
  • Dominik Seichter

    @christ66: Would be great if you could provide a fix. I cannot assign the issue to you, as you are not in the list "assigned".

     
  • Steven Christou

    Steven Christou - 2011-08-29

    Can you check to see if this is still a bug in trunk pmd? I wrote a few test units and they all seem to pass.

     
  • Dominik Seichter

    Hi,

    I just checked with latest trunk and still get a warning. I used the following test file:

    1:
    2: class TestClass {
    3:
    4: public void testMethod() {
    5: char[] idFormat = {'0', '0', '0', '0', '0'};
    6: String abc = "1" + String.valueOf(idFormat); // PMD reports a warning here
    7: System.out.println(abc); // Output 100000
    8: }
    9:}

    And this command:
    _./pmd.sh TestClass.java text ../rulesets/java/strings.xml
    /home/dominik/pmd/pmd/bin/TestClass.java:6 No need to call String.valueOf to append to a string.

    As you can see, it reports a warning.

     
  • Romain PELISSE

    Romain PELISSE - 2012-02-24

    FYI: I confirm the bug. I can indeed reproduce it.

     
  • Andreas Dangel

    Andreas Dangel - 2013-03-16
    • status: open --> in-progress
    • assigned_to: Steven Christou --> Andreas Dangel
    • module: --> PMD
    • milestone: --> PMD-5.0.3
    • priority: 5 --> 3-Major
    • type: --> Bug
    • affects_version: -->
     
  • Andreas Dangel

    Andreas Dangel - 2013-03-17
    • status: in-progress --> closed
     

Log in to post a comment.