JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
Java


JAVA.TYPE.ARRAYTOSTRING : toString on Array (Java)

Summary

toString() is called over an array.

Arrays are instances of java.lang.Object in Java. As a consequence, all methods of java.lang.Object can be invoked on arrays, However, this is not always sensible. In particular, calls to toString() yield a string derived from the unique identifier of the object, which is likely to be useless for the programmer and not her intent when she called toString().

Properties

Class Name toString on Array (Java)
Significance reliability
Mnemonic JAVA.TYPE.ARRAYTOSTRING
Categories
CWE CWE:440 Expected Behavior Violation
Availability Available for Java and Kotlin.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="toString on Array (Java)"

Example

public class CallsOnArray {
  private static A[] array;

  public static void main(String[] args) {
    array = new A[args.length];
    for (int pos = 0; pos < args.length; pos++)
      array[pos] = new A(args[pos]);

    foo(array);

    System.out.println(array); // "toString on Array (Java)" warning issued here
  }

  private static void foo(Object o) {
    String s = o.toString();   // "toString on Array (Java)" warning issued here
    System.out.println(s);
  }

  private static class A {
    private int f;

    private A(String s) {
      this.f = s.length();
    }

    @Override
    public String toString() {
      return String.valueOf(f);
    }
  }
}

In this example, the programmer could replace the call to System.out.println(array) with a loop:

for (int pos = 0; pos < array.length; pos++)
  System.out.println(array[pos]);

Resolution

Replace the call with a call to java.util.Arrays.toString(array) or with an explicit iteration over the elements of the array.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.

 

To report problems with this documentation, please visit https://support.codesecure.com/.