Check two float arrays for equality in Java

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 10-Dec-2018 12:11:22
Advertisements