Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: simplified / corrected examples

...

This noncompliant code example uses the Object.equals() method to compare two arrays.

Code Block
bgColor#FFCCCC
public void arraysEqual() {
  int[] arr1 = new int[20]; // initialized to 0
  int[] arr2 = new int[20]; // initialized to 0
  System.out.println(arr1.equals(arr2)); // prints false
}

Compliant Solution

This compliant solution compares the content of two arrays using the two-argument Arrays.equals() method.

Code Block
bgColor#ccccff
public void arrayContentsEqual() {
  int[] arr1 = new int[20]; // initialized to 0
  int[] arr2 = new int[20]; // initialized to 0
  System.out.println(Arrays.equals(arr1, arr2);) // prints true
}

Compliant Solution

This compliant solution compares the array references using the reference equality operators ==.

Code Block
bgColor#ccccff
public void arrayReferencesEqual(int[] arr1 = new int[20] arr1, ; // initialized to 0
int[] arr2) {
   = new int[20]; // initialized to 0
System.out.println(arr1 == arr2); // prints false 
}

Risk Assessment

Using the equals() method or relational operators with the intention of comparing array contents produces incorrect results, which can lead to vulnerabilities.

...

EXP01-J. Never dereference null pointers      02. Expressions (EXP)