Compare Two Double Arrays Through a Java Program

Share Your Love

In this post, we are going to solve the problem of comparing two double arrays through a java program.

Only double data type values are stored in a Java double array. A double array’s elements have a default value of 0.

We can compare two double arrays in two ways:

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

Method 1: Navigate Approach

By travelling over both arrays using a for loop, one element at a time is compared.

Join Our Community

Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.

// 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");
		}
	}
}

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 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");
	}
}

Output:

Arrays are Equal

Time Complexity: O(1)

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter