Java Array mismatch() Method with Examples
Last Updated :
15 Nov, 2024
The mismatch()
method in Java is a utility from the java.util.Arrays
class. It is used to compare two arrays element by element and determines the index of the first mismatch. It is quite useful to check whether two arrays contain the same corresponding elements or not.
Note: If both arrays have corresponding elements same then this function returns -1.
Mismatched Arrays: It is one of the most basic conditions where the values of arrays are different method responds with the array index where values are unequal.
Java
// Java program to demonstrate the working of
// mismatch() method with arrays
import java.util.Arrays;
class Main {
public static void main(String[] args){
int a[] = { 2, 7, 11, 22, 37 };
int b[] = { 2, 7, 19, 31, 39, 56 };
// Return the first index at which a
// and b have the different element
int i = Arrays.mismatch(a,b);
System.out.println("Index mismatch for arrays: " + i);
}
}
OutputIndex mismatch for arrays: 2
Syntax of mismatch() Method
Arrays.mismatch( a , b );
Parameters: The above method accepts the following parameters:
- a: first array name of a particular data type.
- b: second array name of the same type.
Return value:
- -1: If both the arrays have same elements at all the corresponding positions.
- non-negative integer: The index at which both the arrays have first unequal elements.
Note: The data type of both arrays must be the same, and this method follows zero-based indexing.
Example 1 : For Identical Arrays
Java
// Java program to demonstrate the working of
// mismatch() method with arrays of integer type
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// Initializing an integer arrays
int a[] = { 2, 7, 11, 22, 37 };
int b[] = { 2, 7, 11, 22, 37 };
// Return the first index at which a
// and b have the different element
int i = Arrays.mismatch(a,b);
System.out.println("Index mismatch for arrays: " + i);
}
}
OutputIndex mismatch for arrays: -1
Example 2: Arrays with Different Lengths
It seems that it work with int Array only but this is not the case we can use it with different data types and with different length too as mentioned below:
Java
// Java program to demonstrate the working of
// mismatch() method with arrays of double type
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// Initializing an array containing
// double values
double a[] = { 11.21, 22.31, 33.15, 44.18};
double b[] = { 11.21, 22.31, 33.15, 44.18};
double c[] = { 11.21, 22, 33, 44, 55, 66 };
// Return the first index at which a
// and b have the different element
int i1 = Arrays.mismatch(a,b);
int i2 = Arrays.mismatch(a,c);
System.out.println("Arrays are equal : " + i1);
System.out.println("Arrays are not equal : " + i2);
}
}
OutputArrays are equal : -1
Arrays are not equal : 1
It explains both the cases when the arrays have same values and unequal.