Check two float arrays for equality in Java


To check two float arrays for equality, use the Arrays.equals() method.

In our example, we have the following two float arrays.

float[] floatVal1 = new float[] { 3.2f, 5.5f, 5.3f };
float[] floatVal2 = new float[] { 3.2f, 5.5f, 5.3f };

Let us now compare them for equality.

if (Arrays.equals(floatVal1, floatVal2)) {
System.out.println("Both are equal!");
}

The following is an example wherein we compare arrays and with that also use == to check for other conditions.

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String args[]) {
      float[] floatVal1 = new float[] { 3.2f, 5.5f, 5.3f };
      float[] floatVal2 = new float[] { 3.2f, 5.5f, 5.3f };
      if (floatVal1 == null) {
         System.out.println("First array is null!");
      }
      if (floatVal2 == null) {
         System.out.println("Second array is null!");
      }
      if (floatVal1.length != floatVal2.length) {
         System.out.println("Both does not have equal number of elements!");
      }
      if (Arrays.equals(floatVal1, floatVal2)) {
         System.out.println("Both are equal!");
      }
   }
}

Output

Both are equal!

Updated on: 26-Jun-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements