Skip to Content

Compare Two Java float Arrays Example

  1. /*
  2.   Compare Two Java float Arrays Example
  3.   This java example shows how to compare two float arrays for equality using
  4.   Arrays.equals method.
  5. */
  6.  
  7. import java.util.Arrays;
  8.  
  9. public class CompareFloatArraysExample {
  10.  
  11.   public static void main(String[] args) {
  12.     //create float arrays
  13.     float[] floatArray1 = new float[]{459.432f,348.43f,5832.327f};
  14.     float[] floatArray2 = new float[]{459.432f,348.43f,5832.327f};
  15.    
  16.     /*
  17.       To compare two float arrays use,
  18.       static boolean equals(float array1[], float array2[]) method of Arrays class.
  19.      
  20.       It returns true if both arrays are equal. Arrays are considered as equal
  21.       if they contain same elements in same order.
  22.      
  23.       Two float elements are considered as equal if
  24.       new Float(d1).equals(new Float(d2))
  25.     */
  26.    
  27.     boolean blnResult = Arrays.equals(floatArray1,floatArray2);
  28.     System.out.println("Are two float arrays equal ? : " + blnResult);
  29.    
  30.     /*
  31.       Please note that two float array references pointing to null are
  32.       considered as equal.
  33.       Also, two NaN values are considerd equal. But 0.0f and -0.0f are
  34.       considered as unequal.
  35.     */
  36.    
  37.   }
  38. }
  39.  
  40. /*
  41. Output of the program would be
  42. Are two float arrays equal ? : true
  43. */