Arrays.mismatch(char[], char[]) in Java

Arrays.mismatch(char[], char[]): This method is available in java.util.Arrays class of Java.

Syntax:

int java.util.Arrays.mismatch(char[] a, char[] b)

This method takes two arguments of type char array as its parameters. This method finds and returns the index of the first mismatch between two char arrays, otherwise, return -1 if no mismatch is found.

Note: If the two arrays share a common prefix then the returned index is the length of the common prefix.

Parameters: Two parameters are required for this method.

a: the first array to be tested for a mismatch.

b: the second array to be tested for a mismatch.

Returns: the index of the first mismatch between the two arrays, otherwise -1.

Throws:

NullPointerException - if either array is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;

public class Arraysmismatchchar {
    public static void main(String[] args) {

        char a[] = { 'a', 'b', 'c', 'd' };

        char b[] = { 'a', 'b', 'd', 'c' };

        System.out.println(Arrays.mismatch(a, b));
    }
}

Output:

2


Approach 2: NullPointerException 

Java

import java.util.Arrays;

public class Arraysmismatchchar {
    public static void main(String[] args) {

        char a[] = null;

        char b[] = { 'a', 'b', 'd', 'c' };

        System.out.println(Arrays.mismatch(a, b));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "a" is null at java.base/java.util.Arrays.mismatch(Arrays.java:7710)



No comments:

Post a Comment