In this tutorial you will learn about the Java Program to Compare Two Arrays and its application with practical example.
Java Program to Compare Two Arrays
In this tutorial, we will learn to create a Java program that will Compare Two Arrays using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operators in Java Programming.
What is Compare?
In comparing, we compare two or more things point to point and find the common things or the differences in them.
Compare Two Arrays.
In this program, First, we will declare arrays one and two for the program. Then we will compare them from each other. Then, if they satisfy the conditional statements, they will print that the arrays are the same. If not then satisfy the conditional statements then will print that the arrays are not the same. With the help of this program, we can Compare Two Arrays in an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class Compare2Array { // main method public static void main(String[] args) { // declare and initialize arrays int arr1[] = {10,20,30,40,50}; int arr2[] = arr1; int arr3[] = {10,20,30,40,50}; int arr4[] = {15,25,35,45,55}; // compare arrays using == operator // compare arr1 and arr2 if(arr1 == arr2) System.out.println("array1 & array2 are same"); else System.out.println("array1 & array2 are not same"); // compare arr1 and arr3 if(arr1 == arr3) System.out.println("array1 & array3 are same"); else System.out.println("array1 & array3 are not same"); // compare arr1 and arr4 if(arr1 == arr4) System.out.println("array1 & array4 are same"); else System.out.println("array1 & array4 are not same"); } } |
Output:-
In the above program, we have first initialized the required variable.
- arr1 = it will hold the integer array.
- arr2 = it will hold the integer array.
- arr3 = it will hold the integer array.
- arr4 = it will hold the integer array.
Condition to check for comparison.
Printing if the arrays are the same.
Printing if the arrays are not the same.