how to compare elements in an array java code example

Example 1: compare arrays java

import java.util.Arrays; 
class Test 
{ 
    public static void main (String[] args)  
    { 
        // inarr1 and inarr2 have same values 
        int inarr1[] = {1, 2, 3}; 
        int inarr2[] = {1, 2, 3};    
        Object[] arr1 = {inarr1};  // arr1 contains only one element 
        Object[] arr2 = {inarr2};  // arr2 also contains only one element 
        if (Arrays.equals(arr1, arr2)) 
            System.out.println("Same"); 
        else
            System.out.println("Not same"); 
    } 
}

Example 2: compare numbers in array in java

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

Example 3: how to compare elements in an array

for (let i = 0; i < a.length; i++) {
    for (let k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

Tags:

Java Example