Skip to content
Related Articles

Related Articles

Java Program to Compare two Double Arrays
  • Last Updated : 28 Dec, 2020

Java double array is used to store double data type values only. The default value of the elements in a double array is 0.

We can compare two double arrays by two ways:

  1. By naive approach of traversing through the whole array and comparing each element.
  2. By Arrays.equals() method.

Method 1: Naive Approach

  • By Comparing one element at a time by traversing through both the arrays using for loop.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to compare two double arrays
  
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG {
  
    public static void main(String[] args) throws java.lang.Exception
    {    
        // Two double arrays array1 and array2
        double[] array1 = { 1.5, 2.5, 3.5, 4.5 };
        double[] array2 = { 1.5, 2.5, 3.5 };
  
        // when the length of two arrays are not 
        // same, then both the arrays cannot be equal
        // so no need of comparing each element
        if (array1.length != array2.length)
  
            System.out.println("Arrays are not Equal");
        
        else {
            for (int i = 0; i < array1.length; i++)
            {   
                // comparing each and every element
                if (array1[i] != array2[i])
                {
                    System.out.println("Arrays are not Equal");
                    System.exit(0);
                }
            }
            
            System.out.println("Arrays are Equal");
        }
    }
}

chevron_right


Output

Arrays are not Equal

Time Complexity: O(n)



Method 2: Using Arrays.equals() method

Syntax :

public static boolean equals(int[] a, int[] a2)

Parameters : 

  • a1 – one array to be tested for equality
  • a2 – the other array to be tested for equality

Returns : true if the two arrays are equal

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to compare two double arrays
  
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args) throws java.lang.Exception
    {
        double[] array1 = { 1.5, 2.5, 3.5, 4.5 };
        double[] array2 = { 1.5, 2.5, 3.5, 4.5 };
   
        // Arrays.equals() compares the equality
        // of two arrays
        if (Arrays.equals(array1, array2))
            System.out.println("Arrays are Equal");
        else
            System.out.println("Arrays are Not Equal");
    }
}

chevron_right


Output

Arrays are Equal

Time Complexity: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :