30 Frequently Asked Java Array Interview Programs


In this post, I have collected some of the frequently asked Java array interview programs and have tried to write the solutions for them. I hope it will be helpful for you to prepare for the interviews.

30 Frequently Asked Java Array Interview Programs

1) Write a Java program to find duplicate elements in an array?

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
 
public class DuplicatesInArray 
{
    //Method 1 : Brute Force Method
     
    private static void findDuplicatesUsingBruteForce(int[] inputArray)
    {
        for (int i = 0; i < inputArray.length; i++) 
        {
            for (int j = i+1; j < inputArray.length; j++) 
            {
                if(inputArray&#91;i&#93; == inputArray&#91;j&#93;)
                {
                    System.out.println("Duplicate Element : "+inputArray&#91;i&#93;);
                }
            }
        }
    }
     
    //Method 2 : Sorting Method
     
    private static void findDuplicatesUsingSorting(int&#91;&#93; inputArray)
    {
        Arrays.sort(inputArray);
         
        for (int i = 0; i < inputArray.length-1; i++)
        {
            if(inputArray&#91;i&#93; == inputArray&#91;i+1&#93;)
            {
                System.out.println("Duplicate Element : " + inputArray&#91;i&#93;);
            }
        }
    }
     
    //Method 3 : Using HashSet
     
    private static void findDuplicatesUsingHashSet(int&#91;&#93; inputArray)
    {
        HashSet<Integer> set = new HashSet<Integer>();
         
        for (int element : inputArray) 
        {
            if( ! set.add(element))
            {
                System.out.println("Duplicate Element : "+element);
            }
        }
    }
     
    //Method 4 : Using HashMap
     
    private static void findDuplicatesUsingHashMap(int[] inputArray)
    {
        HashMap<Integer, Integer> map = new HashMap<>();
         
        for (int element : inputArray) 
        {   
            if(map.get(element) == null)
            {
                map.put(element, 1);
            }
            else
            {
                map.put(element, map.get(element)+1);
            }
        }
         
        Set<Entry<Integer, Integer>> entrySet = map.entrySet();
         
        for (Entry<Integer, Integer> entry : entrySet) 
        {               
            if(entry.getValue() > 1)
            {
                System.out.println("Duplicate Element : "+entry.getKey()+" - found "+entry.getValue()+" times.");
            }
        }
    }
     
    //Method 5 : Using Java 8 Streams
     
    private static void findDuplicatesUsingJava8(int[] inputArray) 
    {   
        Set<Integer> uniqueElements = new HashSet<>();
         
        Set<Integer> duplicateElements =  Arrays.stream(inputArray)
                                                .filter(i -> !uniqueElements.add(i))
                                                .boxed()
                                                .collect(Collectors.toSet());
         
        System.out.println(duplicateElements);
    }
     
    public static void main(String[] args) 
    {
        int[] inputArray = new int[] {111, 333, 555, 777, 333, 444, 555};
     
        System.out.println("======Duplicates Using Brute Force======");
         
        findDuplicatesUsingBruteForce(inputArray);
         
        System.out.println("======Duplicates Using Sorting======");
         
        findDuplicatesUsingSorting(inputArray);
         
        System.out.println("======Duplicates Using HashSet======");
         
        findDuplicatesUsingHashSet(inputArray);
 
        System.out.println("======Duplicates Using HashMap======");
         
        findDuplicatesUsingHashMap(inputArray);
         
        System.out.println("======Duplicates Using Java 8 Streams======");
         
        findDuplicatesUsingJava8(inputArray);
    }
}

Output :

======Duplicates Using Brute Force======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using Sorting======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using HashSet======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using HashMap======
Duplicate Element : 555 – found 2 times.
Duplicate Element : 333 – found 2 times.
======Duplicates Using Java 8 Streams======
[555, 333]

[Explanation]

Also Read : 110+ Popular Java Interview Programs With Solutions

2) Write a Java program to find second largest element in an array of integers?

public class MainClass
{
    static int secondLargest(int[] input)
    {
        int firstLargest, secondLargest;
 
        //Checking first two elements of input array
 
        if(input[0] > input[1])
        {
            //If first element is greater than second element
 
            firstLargest = input[0];
 
            secondLargest = input[1];
        }
        else
        {
            //If second element is greater than first element
 
            firstLargest = input[1];
 
            secondLargest = input[0];
        }
 
        //Checking remaining elements of input array
 
        for (int i = 2; i < input.length; i++)
        {
            if(input[i] > firstLargest)
            {
                //If element at 'i' is greater than 'firstLargest'
 
                secondLargest = firstLargest;
 
                firstLargest = input[i];
            }
            else if (input[i] < firstLargest && input[i] > secondLargest)
            {
                //If element at 'i' is smaller than 'firstLargest' and greater than 'secondLargest'
 
                secondLargest = input[i];
            }
        }
 
        return secondLargest;
    }
 
    public static void main(String[] args)
    {
        System.out.println(secondLargest(new int[] {45, 51, 28, 75, 49, 42}));
 
        System.out.println(secondLargest(new int[] {985, 521, 975, 831, 479, 861}));
 
        System.out.println(secondLargest(new int[] {9459, 9575, 5692, 1305, 1942, 9012}));
 
        System.out.println(secondLargest(new int[] {47498, 14526, 74562, 42681, 75283, 45796}));
    }
}

Output :

51
975
9459
74562

[Explanation]

3) Write a Java program to check the equality of two arrays?

First Method : Using Iterative Method

public class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {   
        int[] arrayOne = {2, 5, 1, 7, 4};
         
        int[] arrayTwo = {2, 5, 1, 7, 4};
         
        boolean equalOrNot = true;
         
        if(arrayOne.length == arrayTwo.length)
        {
            for (int i = 0; i < arrayOne.length; i++)
            {
                if(arrayOne[i] != arrayTwo[i])
                {
                    equalOrNot = false;
                }
            }
        }
        else
        {
            equalOrNot = false;
        }
         
        if (equalOrNot)
        {
            System.out.println("Two Arrays Are Equal");
        }
        else
        {
            System.out.println("Two Arrays Are Not equal");
        }
    }
}

Second Method : Using Arrays.equals() Method

class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {
        String[] s1 = {"java", "j2ee", "struts", "hibernate"};
 
        String[] s2 = {"jsp", "spring", "jdbc", "hibernate"};
 
        String[] s3 = {"java", "j2ee", "struts", "hibernate"};
 
        System.out.println(Arrays.equals(s1, s2));        //Output : false
 
        System.out.println(Arrays.equals(s1, s3));      //Output : true
    }
}

[Explanation]

Also Read : 25 Java Array Interview Questions And Answers

4) Write a Java program to find all pairs of elements in an integer array whose sum is equal to a given number?

public class PairsOfElementsInArray
{
    static void findThePairs(int inputArray[], int inputNumber)
    {
        //Sorting the given array
 
        Arrays.sort(inputArray);
 
        System.out.println("Pairs of elements whose sum is "+inputNumber+" are : ");
 
        //Initializing i to first index
 
        int i = 0;
 
        //Initializing j to last index
 
        int j = inputArray.length-1;
 
        //Till i crosses j, perform the following task
 
        while (i < j)
        {
            //If inputArray[i]+inputArray[j] is equal to inputNumber
 
            if(inputArray[i]+inputArray[j] == inputNumber)
            {
                //then Print inputArray[i] and inputArray[j]
 
                System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
 
                //Increment i
 
                i++;
 
                //Decrement j
 
                j--;
            }
 
            //If inputArray[i]+inputArray[j] is smaller than inputNumber
 
            else if (inputArray[i]+inputArray[j] < inputNumber)
            {
                //then increment i
 
                i++;
            }
 
            //If inputArray[i]+inputArray[j] is greater than inputNumber
 
            else if (inputArray[i]+inputArray[j] > inputNumber)
            {
                //then decrement j
 
                j--;
            }
        }
    }
 
    public static void main(String[] args)
    {
        findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);
 
        findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);
 
        findThePairs(new int[] {12, 13, 10, 15, 8, 40, -15}, 25);
 
        findThePairs(new int[] {12, 23, 10, 41, 15, 38, 27}, 50);
    }
}

Output :

Pairs of elements whose sum is 10 are :
-10 + 20 = 10
4 + 6 = 10
5 + 5 = 10
Pairs of elements whose sum is 20 are :
-5 + 25 = 20
8 + 12 = 20
9 + 11 = 20
Pairs of elements whose sum is 25 are :
-15 + 40 = 25
10 + 15 = 25
12 + 13 = 25
Pairs of elements whose sum is 50 are :
12 + 38 = 50
23 + 27 = 50

[Explanation]

5) Write a Java program to find continuous sub array whose sum is equal to a given number?

import java.util.Arrays;
 
public class SubArrayWhoseSumIsNumber
{
    static void findSubArray(int[] inputArray, int inputNumber)
    {
        //Initializing sum with the first element of the inputArray
 
        int sum = inputArray[0];
 
        //Initializing starting point with 0
 
        int start = 0;
 
        //Iterating through inputArray starting from second element
 
        for (int i = 1; i < inputArray.length; i++)
        {
            //Adding inputArray[i] to the current 'sum'
 
            sum = sum + inputArray[i];
 
            //If sum is greater than inputNumber then following loop is executed until
 
            //sum becomes either smaller than or equal to inputNumber
 
            while(sum > inputNumber && start <= i-1)
            {
                //Removing starting elements from the 'sum'
 
                sum = sum - inputArray[start];
 
                //Incrementing start by 1
 
                start++;
            }
 
            //If 'sum' is equal to 'inputNumber' then printing the sub array
 
            if(sum == inputNumber)
            {
                System.out.println("Continuous sub array of "+Arrays.toString(inputArray)+" whose sum is "+inputNumber+" is ");
 
                for (int j = start; j <= i; j++)
                {
                    System.out.print(inputArray[j]+" ");
                }
 
                System.out.println();
            }
        }
    }
 
    public static void main(String[] args)
    {
        findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);
 
        findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);
 
        findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);
    }
}

Output :

Continuous sub array of [42, 15, 12, 8, 6, 32] whose sum is 26 is
12 8 6
Continuous sub array of [12, 5, 31, 13, 21, 8] whose sum is 49 is
5 31 13
Continuous sub array of [15, 51, 7, 81, 5, 11, 25] whose sum is 41 is
5 11 25

[Explanation]

Java Array Interview Programs

6) Write a Java program to find the intersection of two arrays?

First Method : Using Iterative Method

class CommonElements
{
    public static void main(String[] args)
    {
        String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};
 
        String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};
 
        HashSet<String> set = new HashSet<String>();
 
        for (int i = 0; i < s1.length; i++)
        {
            for (int j = 0; j < s2.length; j++)
            {
                if(s1[i].equals(s2[j]))
                {
                    set.add(s1[i]);
                }
            }
        }
 
        System.out.println(set);     //OUTPUT : [THREE, FOUR, FIVE]
    }
}

Second Method : Using retainAll() Method

class CommonElements
{
    public static void main(String[] args)
    {
        Integer[] i1 = {1, 2, 3, 4, 5, 4};
 
        Integer[] i2 = {3, 4, 5, 6, 7, 4};
 
        HashSet<Integer> set1 = new HashSet<>(Arrays.asList(i1));
 
        HashSet<Integer> set2 = new HashSet<>(Arrays.asList(i2));
 
        set1.retainAll(set2);
 
        System.out.println(set1);     //Output : [3, 4, 5]
    }
}

[Explanation]

Also Read : 30+ Java Exception Handling Interview Questions And Answers

7) Write a Java program to separate zeros from non-zeros in an integer array?

Moving Zeros To End Of An Array :

public class SeparateZerosFromNonZeros
{
    static void moveZerosToEnd(int inputArray[])
    {
        //Initializing counter to 0
 
        int counter = 0;
 
        //Traversing inputArray from left to right
 
        for (int i = 0; i < inputArray.length; i++)
        {
            //If inputArray[i] is non-zero
 
            if(inputArray[i] != 0)
            {
                //Assigning inputArray[i] to inputArray[counter]
 
                inputArray[counter] = inputArray[i];
 
                //Incrementing the counter by 1
 
                counter++;
            }
        }
 
        //Assigning zero to remaining elements
 
        while (counter < inputArray.length)
        {
            inputArray[counter] = 0;
 
            counter++;
        }
 
        System.out.println(Arrays.toString(inputArray));
    }
 
    public static void main(String[] args)
    {
        moveZerosToEnd(new int[] {12, 0, 7, 0, 8, 0, 3});
 
        moveZerosToEnd(new int[] {1, -5, 0, 0, 8, 0, 1});
 
        moveZerosToEnd(new int[] {0, 1, 0, 1, -5, 0, 4});
 
        moveZerosToEnd(new int[] {-4, 1, 0, 0, 2, 21, 4});
    }
}

Output :

[12, 7, 8, 3, 0, 0, 0]
[1, -5, 8, 1, 0, 0, 0]
[1, 1, -5, 4, 0, 0, 0]
[-4, 1, 2, 21, 4, 0, 0]

Moving Zeros To The Front Of An Array :

public class SeparateZerosFromNonZeros
{
    static void moveZerosToFront(int inputArray[])
    {
        //Initializing counter to position of last element
 
        int counter = inputArray.length-1;
 
        //Traversing the inputArray from right to left
 
        for (int i = inputArray.length-1; i >= 0; i--)
        {
            //If inputArray[i] is non-zero
 
            if(inputArray[i] != 0)
            {
                //Assigning inputArray[i] to inputArray[counter]
 
                inputArray[counter] = inputArray[i];
 
                //Decrementing the counter by 1
 
                counter--;
            }
        }
 
        //Assigning 0 to remaining elements
 
        while (counter >= 0)
        {
            inputArray[counter] = 0;
 
            counter--;
        }
 
        System.out.println(Arrays.toString(inputArray));
    }
 
    public static void main(String[] args)
    {
        moveZerosToFront(new int[] {12, 0, 7, 0, 8, 0, 3});
 
        moveZerosToFront(new int[] {1, -5, 0, 0, 8, 0, 1});
 
        moveZerosToFront(new int[] {0, 1, 0, 1, -5, 0, 4});
 
        moveZerosToFront(new int[] {-4, 1, 0, 0, 2, 21, 4});
    }
}

Output :

[0, 0, 0, 12, 7, 8, 3]
[0, 0, 0, 1, -5, 8, 1]
[0, 0, 0, 1, 1, -5, 4]
[0, 0, -4, 1, 2, 21, 4]

[Explanation]

8) Write a Java program to find all the leaders in an integer array?

public class LeadersInArray
{
    static void findTheLeaders(int inputArray[])
    {
        //Getting the length of input array
 
        int inputArrayLength = inputArray.length;
 
        //Assuming the last element as max
 
        int max = inputArray[inputArrayLength-1];
 
        System.out.println("The leaders in "+Arrays.toString(inputArray)+" are : ");
 
        //Printing the last element as it is always a leader
 
        System.out.println(inputArray[inputArrayLength-1]);
 
        //Traversing the remaining elements from right to left
 
        for (int i = inputArray.length-2; i >= 0; i--)
        {
            //If the element is greater than max
 
            if(inputArray[i] > max)
            {
                //Printing the element
 
                System.out.println(inputArray[i]);
 
                //Updating the max
 
                max = inputArray[i];
            }
        }
    }
 
    public static void main(String[] args)
    {
        findTheLeaders(new int[] {12, 9, 7, 14, 8, 6, 3});
 
        findTheLeaders(new int[] {8, 23, 19, 21, 15, 6, 11});
 
        findTheLeaders(new int[] {55, 67, 71, 57, 51, 63, 38});
 
        findTheLeaders(new int[] {21, 58, 44, 14, 51, 36, 23});
    }
}

Output :

The leaders in [12, 9, 7, 14, 8, 6, 3] are :
3
6
8
14
The leaders in [8, 23, 19, 21, 15, 6, 11] are :
11
15
21
23
The leaders in [55, 67, 71, 57, 51, 63, 38] are :
38
63
71
The leaders in [21, 58, 44, 14, 51, 36, 23] are :
23
36
51
58

[Explanation]

Also Read : 50+ Java Threads Interview Questions And Answers

9) Write a Java program to find a missing number in an integer array?

public class MissingNumberInArray
{
    //Method to calculate sum of 'n' numbers
 
    static int sumOfNnumbers(int n)
    {
        int sum = (n * (n+1))/ 2;
 
        return sum;
    }
 
    //Method to calculate sum of all elements of array
 
    static int sumOfElements(int[] array)
    {
        int sum = 0;
 
        for (int i = 0; i < array.length; i++)
        {
            sum = sum + array[i];
        }
 
        return sum;
    }
 
    public static void main(String[] args)
    {
        int n = 8;
 
        int[] a = {1, 4, 5, 3, 7, 8, 6};
 
        //Step 1
 
        int sumOfNnumbers = sumOfNnumbers(n);
 
        //Step 2
 
        int sumOfElements = sumOfElements(a);
 
        //Step 3
 
        int missingNumber = sumOfNnumbers - sumOfElements;
 
        System.out.println("Missing Number is = "+missingNumber);
    }
}

[Explanation]

10) Write a Java program to convert an array to ArrayList and an ArrayList to array?

[Explanation]

11) Write a Java program to count occurrences of each element in an array?

import java.util.Arrays;
import java.util.HashMap;
 
public class ArrayElementCountExample 
{  
    static void arrayElementCount(int inputArray[])
    {
        //Creating a HashMap object with elements of inputArray as keys and their count as values
         
        HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
         
        //checking every element of the inputArray
         
        for (int i : inputArray) 
        {
            if(elementCountMap.containsKey(i))
            {
                //If element is present in elementCountMap, incrementing it's count by 1
                 
                elementCountMap.put(i, elementCountMap.get(i)+1);
            }
            else
            {
                //If element is not present in elementCountMap, 
                //adding this element to elementCountMap with 1 as it's value
                 
                elementCountMap.put(i, 1);
            }
        }
         
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        System.out.println("Element Count : "+elementCountMap);
    }
     
    public static void main(String[] args) 
    {   
        arrayElementCount(new int[]{4, 5, 4, 5, 4, 6});
         
        System.out.println("-------------------------");
         
        arrayElementCount(new int[]{12, 9, 12, 9, 10, 9, 10, 11});
         
        System.out.println("-------------------------");
         
        arrayElementCount(new int[]{891, 187, 891, 187, 891, 476, 555, 741});
    }   
}

Output :

Input Array : [4, 5, 4, 5, 4, 6]
Element Count : {4=3, 5=2, 6=1}
=======================================
Input Array : [12, 9, 12, 9, 10, 9, 10, 11]
Element Count : {9=3, 10=2, 11=1, 12=2}
=======================================
Input Array : [891, 187, 891, 187, 891, 476, 555, 741]
Element Count : {741=1, 891=3, 187=2, 555=1, 476=1}
=======================================

[Explanation]

Also Read : 60+ Java Strings Quiz Questions

12) Write a Java program to reverse an array without using an additional array?

import java.util.Arrays;
 
public class ArrayReverseExample 
{  
    static void reverseArray(int inputArray[])
    {
        System.out.println("Array Before Reverse : "+Arrays.toString(inputArray));
         
        int temp;
         
        for (int i = 0; i < inputArray.length/2; i++) 
        {
            temp = inputArray[i];
             
            inputArray[i] = inputArray[inputArray.length-1-i];
             
            inputArray[inputArray.length-1-i] = temp;
        }
         
        System.out.println("Array After Reverse : "+Arrays.toString(inputArray));
    }
     
    public static void main(String[] args) 
    {   
        reverseArray(new int[]{4, 5, 8, 9, 10});
         
        System.out.println("-------------------------");
         
        reverseArray(new int[]{12, 9, 21, 17, 33, 7});
         
        System.out.println("-------------------------");
         
        reverseArray(new int[]{891, 569, 921, 187, 343, 476, 555});
    }   
}

Output :

Array Before Reverse : [4, 5, 8, 9, 10]
Array After Reverse : [10, 9, 8, 5, 4]
————————-
Array Before Reverse : [12, 9, 21, 17, 33, 7]
Array After Reverse : [7, 33, 17, 21, 9, 12]
————————-
Array Before Reverse : [891, 569, 921, 187, 343, 476, 555]
Array After Reverse : [555, 476, 343, 187, 921, 569, 891]

[Explanation]

13) Write a Java program to remove duplicate elements from an array?

import java.util.Arrays;
 
public class RemoveDuplicatesJavaExample 
{   
    static void removeDuplicates(int[] arrayWithDuplicates)
    {
        System.out.println("Array With Duplicates : ");
         
        for (int i = 0; i < arrayWithDuplicates.length; i++)
        {
            System.out.print(arrayWithDuplicates[i]+"\t");
        }
         
        //Assuming all elements in input array are unique
         
        int noOfUniqueElements = arrayWithDuplicates.length;
         
        //Comparing each element with all other elements
         
        for (int i = 0; i < noOfUniqueElements; i++) 
        {
            for (int j = i+1; j < noOfUniqueElements; j++)
            {
                //If any two elements are found equal
                 
                if(arrayWithDuplicates[i] == arrayWithDuplicates[j])
                {
                    //Replace duplicate element with last unique element
                     
                    arrayWithDuplicates[j] = arrayWithDuplicates[noOfUniqueElements-1];
                     
                    //Decrementing noOfUniqueElements
                     
                    noOfUniqueElements--;
                     
                    //Decrementing j
                     
                    j--;
                }
            }
        }
         
        //Copying only unique elements of arrayWithDuplicates into arrayWithoutDuplicates
         
        int[] arrayWithoutDuplicates = Arrays.copyOf(arrayWithDuplicates, noOfUniqueElements);
         
        //Printing arrayWithoutDuplicates
         
        System.out.println();
         
        System.out.println("Array Without Duplicates : ");
         
        for (int i = 0; i < arrayWithoutDuplicates.length; i++)
        {
            System.out.print(arrayWithoutDuplicates[i]+"\t");
        }
         
        System.out.println();
         
        System.out.println("==============================");
    }
     
    public static void main(String[] args) 
    {       
        removeDuplicates(new int[] {4, 3, 2, 4, 9, 2});
         
        removeDuplicates(new int[] {1, 2, 1, 2, 1, 2});
         
        removeDuplicates(new int[] {15, 21, 11, 21, 51, 21, 11});
         
        removeDuplicates(new int[] {7, 3, 21, 7, 34, 18, 3, 21});
    }   
}

[Explanation]

14) Write a Java program to find union and intersection of multiple arrays?

Union Of Multiple Arrays :

import java.util.Arrays;
import java.util.HashSet;
 
public class MainClass
{   
    static void union(int[] ... inputArrays)
    {
        HashSet<Integer> unionSet = new HashSet<Integer>();
         
        System.out.println("Input Arrays :");
         
        System.out.println("======================");
         
        for (int[] inputArray : inputArrays) 
        {
            System.out.println(Arrays.toString(inputArray));
             
            for (int i : inputArray)
            {
                unionSet.add(i);
            }
        }
         
        System.out.println("===========================");
         
        System.out.println("Union Of All Input Arrays :");
         
        System.out.println("===========================");
         
        System.out.println(unionSet);
    }
     
    public static void main(String[] args)
    {   
        int[] inputArray1 = {2, 3, 4, 7, 1};
         
        int[] inputArray2 = {4, 1, 3, 5};
         
        int[] inputArray3 = {8, 4, 6, 2, 1};
         
        int[] inputArray4 = {7, 9, 4, 1};
         
        union(inputArray1, inputArray2, inputArray3, inputArray4);
    }
}

Output :

Input Arrays :
======================
[2, 3, 4, 7, 1]
[4, 1, 3, 5]
[8, 4, 6, 2, 1]
[7, 9, 4, 1]
===========================
Union Of All Input Arrays :
===========================
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Intersection Of Multiple Arrays :

import java.util.Arrays;
import java.util.HashSet;
 
public class MainClass
{   
    static void intersection(Integer[] ... inputArrays)
    {   
        //Printing input arrays
         
        System.out.println("Input Arrays :");
         
        System.out.println("======================");
         
        for (Integer[] inputArray : inputArrays) 
        {
            System.out.println(Arrays.toString(inputArray));
        }
         
        //Creating HashSet object for first input array
         
        HashSet<Integer> intersectionSet = new HashSet<>(Arrays.asList(inputArrays[0]));
         
        //Calling retainAll() method of first object by passing 2nd, 3rd, 4th... objects
         
        for (int i = 1; i < inputArrays.length; i++) 
        {
            HashSet<Integer> set = new HashSet<>(Arrays.asList(inputArrays[i]));
             
            intersectionSet.retainAll(set);
        }
         
        System.out.println("===========================");
         
        System.out.println("Intersection Of All Input Arrays :");
         
        System.out.println("===========================");
         
        System.out.println(intersectionSet);
    }
     
    public static void main(String[] args)
    {   
        Integer[] inputArray1 = {2, 3, 4, 7, 1};
         
        Integer[] inputArray2 = {4, 1, 3, 5};
         
        Integer[] inputArray3 = {8, 4, 6, 2, 1};
         
        Integer[] inputArray4 = {7, 9, 4, 1};
         
        intersection(inputArray1, inputArray2, inputArray3, inputArray4);
    }
}

Output :

Input Arrays :
======================
[2, 3, 4, 7, 1]
[4, 1, 3, 5]
[8, 4, 6, 2, 1]
[7, 9, 4, 1]
===========================
Intersection Of All Input Arrays :
===========================
[1, 4]

[Explanation]

Also Read : 25 Fresher’s Basic Java Interview Questions

15) Write a Java program to find the most frequent element in an array?

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
 
public class MostFrequentElementProgram
{   
    static void getMostFrequentElement(int inputArray[])
    {
        //Creating HashMap object with elements as keys and their occurrences as values
         
        HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
         
        //Inserting all the elements of inputArray into elementCountMap
         
        for (int i : inputArray) 
        {
            if (elementCountMap.containsKey(i))
            {
                //If an element is present, incrementing its count by 1
                 
                elementCountMap.put(i, elementCountMap.get(i)+1);
            }
            else
            {
                //If an element is not present, put that element with 1 as its value
                 
                elementCountMap.put(i, 1);
            }
        }
         
        int element = 0;
         
        int frequency = 1;
         
        //Iterating through elementCountMap to get the most frequent element and its frequency
         
        Set<Entry<Integer, Integer>> entrySet = elementCountMap.entrySet();
         
        for (Entry<Integer, Integer> entry : entrySet) 
        {
            if(entry.getValue() > frequency)
            {
                element = entry.getKey();
                 
                frequency = entry.getValue();
            }
        }
         
        //Printing the most frequent element in array and its frequency
         
        if(frequency > 1)
        {
            System.out.println("Input Array : "+Arrays.toString(inputArray));
             
            System.out.println("The most frequent element : "+element);
             
            System.out.println("Its frequency : "+frequency);
             
            System.out.println("========================");
        }
        else
        {
            System.out.println("Input Array : "+Arrays.toString(inputArray));
             
            System.out.println("No frequent element. All elements are unique.");
             
            System.out.println("=========================");
        }
    }
     
    public static void main(String[] args)
    {
        getMostFrequentElement(new int[]{4, 5, 8, 7, 4, 7, 6,7});
         
        getMostFrequentElement(new int[]{1, 2, 7, 5, 3, 6});
    }
}

Output :

Input Array : [4, 5, 8, 7, 4, 7, 6, 7]
The most frequent element : 7
Its frequency : 3
========================
Input Array : [1, 2, 7, 5, 3, 6]
No frequent element. All elements are unique.
=========================

[Explanation]

16) Write a Java program to find the minimum absolute difference between any two elements of the given array?

import java.util.Arrays;
 
public class JavaArrayProgram 
{
    private static void minimumAbsoluteDifference(int[] inputArray)
    {   
        Arrays.sort(inputArray);
         
        int minimum = Math.abs(inputArray[1] - inputArray[0]);
         
        int firstElement = inputArray[0];
         
        int secondElement = inputArray[1];
         
        for (int i = 2; i < inputArray.length; i++) 
        {   
            if(Math.abs(inputArray[i] - inputArray[i-1]) < minimum)
            {
                minimum = Math.abs(inputArray[i] - inputArray[i-1]);
                 
                firstElement = inputArray[i-1];
                 
                secondElement = inputArray[i];
            }
        }
         
        System.out.println("Sorted Input Array : "+Arrays.toString(inputArray));
         
        System.out.println("Minimum Absolute Difference : "+minimum);
         
        System.out.println("Pair Of Elements : ("+firstElement+", "+secondElement+")");
    }
     
     
    public static void main(String[] args) 
    {
        minimumAbsoluteDifference(new int[] {5, 8, 4, 2, 9, 0});
         
        System.out.println("==========================");
         
        minimumAbsoluteDifference(new int[] {45, -89, 12, -62, 31, -57});
         
        System.out.println("==========================");
         
        minimumAbsoluteDifference(new int[] {5, -3, 7, -2});
    }
}

Output :

Sorted Input Array : [0, 2, 4, 5, 8, 9]
Minimum Absolute Difference : 1
Pair Of Elements : (4, 5)
==========================
Sorted Input Array : [-89, -62, -57, 12, 31, 45]
Minimum Absolute Difference : 5
Pair Of Elements : (-62, -57)
==========================
Sorted Input Array : [-3, -2, 5, 7]
Minimum Absolute Difference : 1
Pair Of Elements : (-3, -2)

[Explanation]

17) How to sort array elements by frequency in Java?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
 
public class SortArrayElementsByFrequencyProgram 
{
    private static void sortArrayElementsByFrequency(int[] inputArray)
    {
        //Create LinkedHashMap with elements as keys and their occurrences as values
        //Remember LinkedHashMap maintains insertion order of elements
         
        Map<Integer, Integer> elementCountMap = new LinkedHashMap<>();
         
        //Check presence of each element in elementCountMap 
         
        for (int i = 0; i < inputArray.length; i++) 
        {
            if (elementCountMap.containsKey(inputArray[i]))
            {
                //If element is present in elementCountMap, increment its value by 1
                 
                elementCountMap.put(inputArray[i], elementCountMap.get(inputArray[i])+1);
            }
            else
            {
                //If element is not present, insert this element with 1 as its value
                 
                elementCountMap.put(inputArray[i], 1);
            }
        }
         
        //Construct an ArrayList holding all Entry objects of elementCountMap
         
        ArrayList<Entry<Integer, Integer>> listOfEntry = new ArrayList<>(elementCountMap.entrySet());
         
        //Sort listOfEntry based on values
         
        Collections.sort(listOfEntry, new Comparator<Entry<Integer, Integer>>() 
                                        {
                                            @Override
                                            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) 
                                            {
                                                return o2.getValue().compareTo(o1.getValue());
                                            }
                                        }
        );
         
        //Print sorted array elements in descending order of their frequency
         
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        System.out.println("Sorted Array Elements In Descending Order Of Their Frequency :");
         
        System.out.print("[ ");
         
        for (Entry<Integer, Integer> entry : listOfEntry) 
        {
            int frequency = entry.getValue();
             
            while (frequency >= 1)
            {
                System.out.print(entry.getKey()+" ");
                 
                frequency--;
            }
        }
         
        System.out.print("]");
    }
     
    public static void main(String[] args) 
    {
        sortArrayElementsByFrequency(new int[] {7, 1, 3, 4, 7, 1, 7, 1, 4, 5, 1, 9, 3});
    }
}

Output :

Input Array : [7, 1, 3, 4, 7, 1, 7, 1, 4, 5, 1, 9, 3]
Sorted Array Elements In Descending Order Of Their Frequency :
[ 1 1 1 1 7 7 7 3 3 4 4 5 9 ]

[Explanation]

Also Read : 15 Simple But Confusing Java Interview Questions

18) How to merge two sorted or unsorted arrays into single sorted array without duplicates in Java?

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
public class MergeTwoArraysAndRemoveDuplicatesProgram 
{   
    private static int[] mergeArraysAndRemoveDuplicates(int[] arrayA, int[] arrayB)
    {
        //Step 1 : Merging of two arrays
         
        //Defining mergedArray with combined size of arrayA and arrayB
         
        int[] mergedArray = new int[arrayA.length + arrayB.length];
         
        //Initializing pointers of arrayA, arrayB and mergedArray with 0
         
        int i=0, j=0, k=0;
         
        //Inserting all elements of arrayA into mergedArray
         
        while (i < arrayA.length)
        {
            mergedArray[k] = arrayA[i];
            k++;
            i++;
        }
         
        //Inserting all elements of arrayB into mergedArray
         
        while (j < arrayB.length)
        {
            mergedArray[k] = arrayB[j];
            k++;
            j++;
        }
         
        //Step 2 : Removing duplicates from merged array
         
        //Defining one HashSet object called setWithNoDuplicates
        //Remember, HashSet allows only unique elements
         
        Set<Integer> setWithNoDuplicates = new HashSet<>();
         
        //Adding all elements of mergedArray into setWithNoDuplicates
         
        for (int m = 0; m < mergedArray.length; m++) 
        {
            setWithNoDuplicates.add(mergedArray[m]);
        }
         
        //Now, setWithNoDuplicates will have only unique elements of mergedArray
         
        //So, now iterate setWithNoDuplicates and 
        //add its elements into new array called mergedArrayWithNoDuplicates
         
        Iterator<Integer> it = setWithNoDuplicates.iterator();
         
        int[] mergedArrayWithNoDuplicates = new int[setWithNoDuplicates.size()];
         
        int n = 0;
         
        //Adding all elements of setWithNoDuplicates into mergedArrayWithNoDuplicates
         
        while (it.hasNext()) 
        {
            mergedArrayWithNoDuplicates[n] = it.next();
            n++;
        }
         
        //Step 3 : Sorting merged array after removing duplicates
         
        Arrays.sort(mergedArrayWithNoDuplicates);
         
        return mergedArrayWithNoDuplicates;
    }
     
    public static void main(String[] args)
    {
        int[] arrayA = new int[] {7, -5, 3, 8, -4, 11, -19, 21};
         
        int[] arrayB = new int[] {6, 13, -7, 0, 11, -4, 3, -5};
         
        int[] mergedArray = mergeArraysAndRemoveDuplicates(arrayA, arrayB);
         
        System.out.println("Array A : "+Arrays.toString(arrayA));
         
        System.out.println("Array B : "+Arrays.toString(arrayB));
         
        System.out.println("Sorted Merged Array With No Duplicates : ");
         
        System.out.println(Arrays.toString(mergedArray));
    }
}

Output :

Array A : [7, -5, 3, 8, -4, 11, -19, 21]
Array B : [6, 13, -7, 0, 11, -4, 3, -5]
Sorted Merged Array With No Duplicates :
[-19, -7, -5, -4, 0, 3, 6, 7, 8, 11, 13, 21]

[Explanation]

19) How to merge two unsorted arrays in sorted order in Java?

import java.util.Arrays;
 
public class MergeArrayProgram 
{
    private static int[] mergeArray(int[] arrayA, int[] arrayB)
    {
        int[] mergedArray = new int[arrayA.length + arrayB.length];
         
        int i=0, j=0, k=0; 
                 
        while (i < arrayA.length) 
        {
            mergedArray[k] = arrayA[i];
            i++;
            k++;
        } 
                 
        while (j < arrayB.length) 
        {
            mergedArray[k] = arrayB[j];
            j++;
            k++;
        } 
             
        Arrays.sort(mergedArray);
         
        return mergedArray;
    }
     
    public static void main(String[] args) 
    {
        int[] arrayA = new int[] {12, -7, 18, 9, 37, -1, 21};
         
        int[] arrayB = new int[] {27, 8, 71, -9, 18};
         
        int[] mergedArray = mergeArray(arrayA, arrayB);
         
        System.out.println("Array A : "+Arrays.toString(arrayA));
         
        System.out.println("Array B : "+Arrays.toString(arrayB));
         
        System.out.println("Merged Array : "+Arrays.toString(mergedArray));
    }
}

Output :

Array A : [12, -7, 18, 9, 37, -1, 21]
Array B : [27, 8, 71, -9, 18]
Merged Array : [-9, -7, -1, 8, 9, 12, 18, 18, 21, 27, 37, 71]

[Explanation]

20) How to merge two sorted arrays in Java?

import java.util.Arrays;
 
public class MergeArrayProgram 
{
    private static int[] mergeArray(int[] arrayA, int[] arrayB)
    {
        int[] mergedArray = new int[arrayA.length + arrayB.length];
         
        int i=0, j=0, k=0;
         
        while (i < arrayA.length && j < arrayB.length)
        {
            if (arrayA[i] < arrayB[j]) 
            {
                mergedArray[k] = arrayA[i];
                i++;
                k++;
            } 
            else
            {
                mergedArray[k] = arrayB[j];
                j++;
                k++;
            }
        } 
                 
        while (i < arrayA.length) 
        {
            mergedArray[k] = arrayA[i];
            i++;
            k++;
        } 
                 
        while (j < arrayB.length) 
        {
            mergedArray[k] = arrayB[j];
            j++;
            k++;
        } 
             
        return mergedArray;
    }
     
    public static void main(String[] args) 
    {
        int[] arrayA = new int[] {-7, 12, 17, 29, 41, 56, 79};
         
        int[] arrayB = new int[] {-9, -3, 0, 5, 19};
         
        int[] mergedArray = mergeArray(arrayA, arrayB);
         
        System.out.println("Array A : "+Arrays.toString(arrayA));
         
        System.out.println("Array B : "+Arrays.toString(arrayB));
         
        System.out.println("Merged Array : "+Arrays.toString(mergedArray));
    }
}

Output :

Array A : [-7, 12, 17, 29, 41, 56, 79]
Array B : [-9, -3, 0, 5, 19]
Merged Array : [-9, -7, -3, 0, 5, 12, 17, 19, 29, 41, 56, 79]

[Explanation]

Also Read : Quiz On Increment And Decrement Operators

21) Write a Java program to find smallest and second smallest element in an integer array?

import java.util.Arrays;
 
public class SmallestSecondSmallestElementInArray 
{
    private static void getSmallestAndSecondSmallestElement(int[] inputArray)
    {
        int smallest = inputArray[0];
         
        int secondSmallest = inputArray[0];
         
        for (int i = 0; i < inputArray.length; i++) 
        {
            if (inputArray[i] < smallest)
            {
                secondSmallest = smallest;
                 
                smallest = inputArray[i];
            }
            else if (inputArray[i] > smallest && inputArray[i] < secondSmallest)
            {
                secondSmallest = inputArray[i];
            }
        }
         
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        System.out.println("Smallest Element : "+smallest);
         
        System.out.println("Second Smallest Element : "+secondSmallest);
    }
     
    public static void main(String[] args) 
    {
        getSmallestAndSecondSmallestElement(new int[] {17, 11, 23, 64, 41, 88, 35});
         
        System.out.println("===============================");
         
        getSmallestAndSecondSmallestElement(new int[] {-9, 3, 36, -25, -9, 71, 0});
         
        System.out.println("===============================");
         
        getSmallestAndSecondSmallestElement(new int[] {21, 21, -18, -4, -11, 85, 7});
    }
}

Output :

Input Array : [17, 11, 23, 64, 41, 88, 35]
Smallest Element : 11
Second Smallest Element : 17
===============================
Input Array : [-9, 3, 36, -25, -9, 71, 0]
Smallest Element : -25
Second Smallest Element : -9
===============================
Input Array : [21, 21, -18, -4, -11, 85, 7]
Smallest Element : -18
Second Smallest Element : -11

[Explanation]

22) Write a Java program to find contiguous sub array with maximum sum?

import java.util.Arrays;
 
public class MaximumSubArrayProblem 
{
    private static void getSubArrayWithMaxSum(int[] inputArray)
    {
        //Initializing bestSum to first element of input array and
        //bestStart and bestEnd to first index i.e 0
         
        int bestSum = inputArray[0];
        int bestStart = 0;
        int bestEnd = 0;
         
        //Initializing currentSum and currentStart to 0
         
        int currentSum = 0;
        int currentStart = 0;
         
        for (int i = 0; i < inputArray.length; i++)
        {
            //Adding current element to currentSum
             
            currentSum = currentSum + inputArray[i];
             
            //If currentSum becomes negative, clearing currentSum and
            //setting currentStart to next element
             
            if(currentSum < 0)
            {
                currentSum = 0;
                currentStart = i+1;
            }
             
            // If currentSum exceeds bestSum, assigning currentSum to bestSum and 
            //updating bestStart and bestEnd
             
            else if (currentSum > bestSum)
            {
                bestSum = currentSum;
                bestStart = currentStart;
                bestEnd = i;
            }
        }
         
        //Printing sub array with bestSum
         
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        System.out.print("Continous Sub Array With Maximum Sum : ");
         
        System.out.print("[ ");
         
        for (int i = bestStart; i <= bestEnd; i++) 
        {
            System.out.print(inputArray[i]+" ");
        }
         
        System.out.print("]");
         
        System.out.println();
         
        System.out.println("Sum : "+bestSum);
    }
     
    public static void main(String[] args) 
    {
        getSubArrayWithMaxSum(new int[] {2, -3, 7, -4, 2, 5, -8, 6, -1});
    }
}

Output :

Input Array : [2, -3, 7, -4, 2, 5, -8, 6, -1]
Continous Sub Array With Maximum Sum : [ 7 -4 2 5 ]
Sum : 10

[Explanation]

23) Write a Java program which prints all contiguous sub arrays with given sum?

import java.util.Arrays;
import java.util.HashMap;
 
public class ContigousSubArrayWithGivenSum 
{
    private static void hashingMethod(int[] inputArray, int givenSum)
    {
        System.out.println("Given Array : "+Arrays.toString(inputArray));
         
        System.out.println("Given Sum : "+givenSum);
         
        System.out.println("Contiguous Sub Arrays With Sum "+givenSum+" Are : ");
         
        //Initializing currentSum to 0
         
        int currentSum = 0;
         
        //Defining sumIndexMap with currentSum as keys and index as values
         
        HashMap<Integer, Integer> sumIndexMap = new HashMap<>();
         
        //Inserting 0 as key and 1 as value into sumIndexMap
         
        sumIndexMap.put(0, -1);
         
        //Iterating each element of inputArray
         
        for (int i = 0; i < inputArray.length; i++) 
        {
            //Adding current element to currentSum
             
            currentSum = currentSum + inputArray[i];
             
            //Checking whether sumIndexMap contains (currentSum - givenSum)
             
            if (sumIndexMap.containsKey(currentSum - givenSum)) 
            {   
                //If it contains, printing sub array
                 
                printSubArray(inputArray, sumIndexMap.get(currentSum - givenSum)+1, i);
            }
             
            //Inserting currentSum as key and i as its value into sumIndexMap
             
            sumIndexMap.put(currentSum, i); 
        }
    }
     
    //Utility Method To Print Sub Array
     
    private static void printSubArray(int[] inputArray, int start, int end)
    {
        System.out.print("[");
         
        for (int i = start; i <= end; i++) 
        {
            System.out.print(" "+inputArray[i]);
        }
         
        System.out.println(" ]");
    }
     
    public static void main(String[] args) 
    {
        hashingMethod(new int[] {2, 4, 2, 8, 3, 3, 2, -4, 12}, 8);
         
        System.out.println("=====================================");
         
        hashingMethod(new int[] {5, -9, 4, -2, 7, 1, -4, -3, -7}, -7);
         
        System.out.println("=====================================");
         
        hashingMethod(new int[] {7, 3, 6, 5, 21, -6, -15, 28, 8}, 21);
    }
}

Output :

Given Array : [2, 4, 2, 8, 3, 3, 2, -4, 12]
Given Sum : 8
Contiguous Sub Arrays With Sum 8 Are :
[ 2 4 2 ]
[ 8 ]
[ 3 3 2 ]
[ -4 12 ]
=====================================
Given Array : [5, -9, 4, -2, 7, 1, -4, -3, -7]
Given Sum : -7
Contiguous Sub Arrays With Sum -7 Are :
[ -9 4 -2 ]
[ -4 -3 ]
[ -7 ]
=====================================
Given Array : [7, 3, 6, 5, 21, -6, -15, 28, 8]
Given Sum : 21
Contiguous Sub Arrays With Sum 21 Are :
[ 7 3 6 5 ]
[ 21 ]
[ 7 3 6 5 21 -6 -15 ]
[ -15 28 8 ]

[Explanation]

24) How to sort an array of 0s and 1s in Java?

import java.util.Arrays;
 
public class Array0s1sProgram 
{   
    private static void sortBinaryArray(int[] inputArray)
    {
        int left = 0;
         
        int right = inputArray.length-1;
         
        System.out.println("Input Array Before Sorting : "+Arrays.toString(inputArray));
         
        while (left < right)
        {
            if (inputArray[left] == 1)
            {
                //Swapping
                 
                inputArray[right] = inputArray[right] + inputArray[left];
                inputArray[left] = inputArray[right] - inputArray[left];
                inputArray[right] = inputArray[right] - inputArray[left];
                 
                right--;
            }
            else
            {
                left++;
            }
        }
         
        System.out.println("Input Array After Sorting : "+Arrays.toString(inputArray));
    }
     
    public static void main(String[] args) 
    {
        sortBinaryArray(new int[] {1, 0, 1, 1, 0, 1, 0, 0});
         
        System.out.println("============================");
         
        sortBinaryArray(new int[] {1, 1, 1, 1, 0, 0, 0, 0});
         
        System.out.println("============================");
         
        sortBinaryArray(new int[] {1, 1, 0, 0, 1, 1, 0, 0});
    }
}

Output :

Input Array Before Sorting : [1, 0, 1, 1, 0, 1, 0, 0]
Input Array After Sorting : [0, 0, 0, 0, 1, 1, 1, 1]
============================
Input Array Before Sorting : [1, 1, 1, 1, 0, 0, 0, 0]
Input Array After Sorting : [0, 0, 0, 0, 1, 1, 1, 1]
============================
Input Array Before Sorting : [1, 1, 0, 0, 1, 1, 0, 0]
Input Array After Sorting : [0, 0, 0, 0, 1, 1, 1, 1]

[Explanation]

25) How to sort an array of 0s, 1s and 2s in Java?

import java.util.Arrays;
 
public class SortArrayOf0s1s2sProgram 
{
    private static void sortArray(int[] inputArray)
    {
        System.out.println("Array Before Sorting : "+Arrays.toString(inputArray));
         
        //Initializing low and mid to 0
         
        int low = 0; 
         
        int mid = 0; 
                 
        //and high to last index
         
        int high = inputArray.length-1;
         
        //Until mid doesn't cross high
         
        while (mid <= high)
        {
            //If an element is 0, bring it to the beginning
             
            if (inputArray[mid] == 0)
            {
                swap(inputArray, low, mid);
                low++;
                mid++;
            }
             
            //If an element is 2, send it to the end
             
            else if (inputArray[mid] == 2)
            {
                swap(inputArray, mid, high);
                high--;
            }
             
            //If an element is 1, let it be there only
             
            else
            {
                mid++;
            }
        }
         
        System.out.println("Array After Sorting : "+Arrays.toString(inputArray));
    }
     
    //Utility method for swapping
     
    private static void swap(int[] inputArray, int i, int j)
    {
        int temp = inputArray[i];
        inputArray[i] = inputArray[j];
        inputArray[j] = temp;
    }
     
    public static void main(String[] args) 
    {
        sortArray(new int[] {1, 0, 2, 2, 0, 2, 1, 2, 1, 1, 2, 0});
         
        System.out.println("=====================================");
         
        sortArray(new int[] {1, 2, 0, 2, 0, 1, 0, 2, 1, 0, 0, 2});
         
        System.out.println("=====================================");
         
        sortArray(new int[] {2, 1, 0, 0, 1, 2, 2, 0, 1, 0, 2, 1});
         
        System.out.println("=====================================");
    }
}

Output :

Array Before Sorting : [1, 0, 2, 2, 0, 2, 1, 2, 1, 1, 2, 0]
Array After Sorting : [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
=====================================
Array Before Sorting : [1, 2, 0, 2, 0, 1, 0, 2, 1, 0, 0, 2]
Array After Sorting : [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
=====================================
Array Before Sorting : [2, 1, 0, 0, 1, 2, 2, 0, 1, 0, 2, 1]
Array After Sorting : [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
=====================================

[Explanation]

26) Write a Java program which finds triplets in the given array whose sum is equal to given number?

import java.util.Arrays;
 
public class JavaArrayTripletSum 
{
    private static void getArrayTriplets(int[] inputArray, int sum)
    {
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        System.out.println("Given Number : "+sum);
         
        System.out.println("Array triplets whose sum is "+sum+" are :");
         
        //Method 3 : Using Sorting
         
        Arrays.sort(inputArray);
         
        for (int i = 0; i < inputArray.length-2; i++) 
        {
            int left = i+1;
             
            int right = inputArray.length-1;
             
            while (left < right)
            {
                if (inputArray[i] + inputArray[left] + inputArray[right] == sum) 
                {
                    System.out.println("["+inputArray[i] + ", " + inputArray[left] + ", " + inputArray[right]+"]");
                     
                    left++;
                     
                    right--;
                } 
                else if (inputArray[i] + inputArray[left] + inputArray[right] < sum)
                {
                    left++;
                }
                else
                {
                    right--;
                }
            }
        }
    }
     
    public static void main(String[] args) 
    {
        getArrayTriplets(new int[] {7, 5, 9, 3, 0, 8, 6}, 12);
 
        System.out.println("===========================");
         
        getArrayTriplets(new int[] {-3, 7, -1, -5, 2, -9, 1}, 0);
         
        System.out.println("===========================");
         
        getArrayTriplets(new int[] {17, 51, 39, 29, 33, 21, 65}, 89);
    }
}

Output :

Input Array : [7, 5, 9, 3, 0, 8, 6]
Given Number : 12
Array triplets whose sum is 12 are :
[0, 3, 9]
[0, 5, 7]
===========================
Input Array : [-3, 7, -1, -5, 2, -9, 1]
Given Number : 0
Array triplets whose sum is 0 are :
[-9, 2, 7]
[-3, 1, 2]
===========================
Input Array : [17, 51, 39, 29, 33, 21, 65]
Given Number : 89
Array triplets whose sum is 89 are :
[17, 21, 51]
[17, 33, 39]
[21, 29, 39]

[Explanation]

27) Write a Java program to find array triplets such that sum of first two elements equals the third element?

import java.util.Arrays;
import java.util.HashSet;
 
public class ArrayTripletsJavaProgram 
{
    private static void getArrayTriplets(int[] inputArray)
    {
        System.out.println("Input Array : "+Arrays.toString(inputArray));
         
        //Creating HashSet called elementSet
         
        HashSet<Integer> elementSet = new HashSet<>();
         
        //Adding all elements into elementSet
         
        for (int i = 0; i < inputArray.length; i++) 
        {
            elementSet.add(inputArray[i]);
        }
         
        System.out.println("Array triplets with sum of first two elements equals third :");
         
        for (int i = 0; i < inputArray.length-1; i++) 
        {
            for (int j = i+1; j < inputArray.length; j++) 
            {
                //Checking whether elementSet contains sum of any two elements
                 
                if (elementSet.contains(inputArray[i]+inputArray[j])) 
                {
                    System.out.println("["+inputArray[i]+", "+inputArray[j]+", "+(inputArray[i]+inputArray[j])+"]");
                }
            }
        }
    }
     
    public static void main(String[] args) 
    {
        getArrayTriplets(new int[] {21, 13, 47, 61, 34, 40, 55, 71, 87});
         
        System.out.println("===========================================");
         
        getArrayTriplets(new int[] {-1, 3, -2, 1, -4, 0, 5, 2, -3});
         
        System.out.println("===========================================");
         
        getArrayTriplets(new int[] {1, 3, 9, 2, 6, 4, 8, 5, 7});
    }
}

[Explanation]

28) Array Rotation Program In Java

Left Rotation :

import java.util.Arrays;
 
public class ArrayRotationProgram 
{
    private static void leftRotate(int[] inputArray, int n) 
    {
        System.out.println("Input Array Before Rotation :");
         
        System.out.println(Arrays.toString(inputArray));
         
        int temp;
         
        for (int i = 0; i < n; i++)
        {
            temp = inputArray[0];
             
            for (int j = 0; j < inputArray.length-1; j++) 
            {
                inputArray[j] = inputArray[j+1];
            }
             
            inputArray[inputArray.length - 1] = temp;
        }
         
        System.out.println("Input Array After Left Rotation By "+n+" Positions :");
         
        System.out.println(Arrays.toString(inputArray));
    }
     
    public static void main(String[] args) 
    {
        leftRotate(new int[] {1,2,3,4,5,6,7}, 2);
    }
}

Output :

Input Array Before Rotation :
[1, 2, 3, 4, 5, 6, 7]
Input Array After Left Rotation By 2 Positions :
[3, 4, 5, 6, 7, 1, 2]

Right Rotation :

import java.util.Arrays;
 
public class ArrayRotationProgram 
{
    private static void rightRotate(int[] inputArray, int n)
    {
        System.out.println("Input Array Before Rotation :");
         
        System.out.println(Arrays.toString(inputArray));
         
        int temp;
         
        for (int i = 1; i <= n; i++) 
        { 
            temp = inputArray[inputArray.length-1]; 
             
            for (int j = inputArray.length-1; j > 0; j--) 
            {
                inputArray[j] = inputArray[j-1];
            }
             
            inputArray[0] = temp;
        }
         
        System.out.println("Input Array After Right Rotation By "+n+" Positions :");
         
        System.out.println(Arrays.toString(inputArray));
    }
     
    public static void main(String[] args) 
    {
        rightRotate(new int[] {1,2,3,4,5,6,7}, 2);
    }
}

Output :

Input Array Before Rotation :
[1, 2, 3, 4, 5, 6, 7]
Input Array After Right Rotation By 2 Positions :
[6, 7, 1, 2, 3, 4, 5]

[Explanation]

29) Array Element Removal Programs. [Explanation]

30) Arrays.deepToString() method example. [Explanation]


27 Comments

    • public class ArrayCycle {

      public static void main(String[] args)
      {
      int arr[]={1,2,3,4,5,6,7,8,9};
      Rotate r=new Rotate();
      int arr1[]=r.rotateClockWise(arr).clone();
      System.out.println(“After rotating Clockwise”);
      for(int i=0;i<arr.length;i++)
      {
      System.out.println(arr1[i]);
      }

      int arr2[]=r.rotateAntiClockWise(arr).clone();
      System.out.println("After rotating AntiClockwise");
      for(int i=0;i<arr.length;i++)
      {
      System.out.println(arr2[i]);
      }
      }
      }

      class Rotate
      {
      int[] rotateClockWise(int arr[])
      {
      int length=arr.length;
      int temp[]=new int[length];

      for(int i=1;i<arr.length;i++)
      {
      temp[i-1]=arr[i];
      }
      temp[length-1]=arr[0];
      return temp;
      }

      int[] rotateAntiClockWise(int arr[])
      {
      int length=arr.length;
      int temp[]=new int[length];

      for(int i=0;i<arr.length-1;i++)
      {
      temp[i+1]=arr[i];
      }
      temp[0]=arr[length-1];
      return temp;
      }
      }

  1. The following program does not produce the result. Pls check and update
    5) Write a java program to find continuous sub array whose sum is equal to a given number?

    • import java.util.Arrays;

      public class SubArrayWithSum {
      static void findSubArray(int[] inputArray, int inputNumber)
      {
      //Initializing sum with the first element of the inputArray

      int sum = inputArray[0];

      //Initializing starting point with 0

      int start = 0;
      int strtPt = 0;

      //Iterating through inputArray starting from second element

      for (int i = 1; i inputNumber && start inputNumber) {
      sum = inputArray[i];
      strtPt = i;
      }

      start++;
      }

      //If ‘sum’ is equal to ‘inputNumber’ then printing the sub array

      if(sum == inputNumber)
      {
      System.out.println(“Input Array : “+Arrays.toString(inputArray));

      System.out.println(“Input Number : “+inputNumber);

      System.out.print(“Continuous Sub Array : “);

      for (int j = strtPt; j <= i; j++)
      {
      System.out.print(inputArray[j]+" ");
      }

      System.out.println();
      }
      }

      System.out.println("=================================");
      }

      public static void main(String[] args)
      {
      findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);

      findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);

      findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);
      }
      }

  2. Some programs i tried with my own array data but some extra logic u need to Add please check Max two number and continuous Number sum is wrong please check.

    • #include
      int main()

      {
      int arr[] = {2,4,8,5,12,15,6,10,7,30,25,43,46,45,21};
      int i,j,temp;
      int count=0;
      printf(“Input Array :”);
      for(i=0;i<15;i++)
      {
      printf("%d,",arr[i]);
      }printf("\n");
      for(i=0;i<15;i++)

      {
      if(i%5==0){
      count++;
      }
      }
      for(i=0;i=0;j–)
      {
      if(arr[j]%5!=0)
      {
      temp=arr[i];
      arr[i]=arr[j];
      arr[j]=temp;
      break;
      }
      }
      }

      }
      printf(“Output Array :”);
      for(i=0;i<15;i++)
      {
      printf("%d,",arr[i]);
      }

      }

  3. write a program to transform input array into output array.

    Input Array : 2,4,8,5,12,15,6,10,7,30,25,43,46,45,21

    Output Array : 2,4,8, 12, 6, 7, 43,46,21, 5,15,10,30,25,45

    Do not use duplicate or extra array.

  4. Hi Admin,
    May I know,how to solve this programme:-
    String s1 ={abcdefghj197scggg5dcmkktt79ddc};
    I want output like this:-
    197+5+79=281

    Thanks
    Aneesh

    • Not the admin but a fellow programmer. I hope I’m not too late.

      public static void main(String[] args){
      String s1 = “{abcdefghj197scggg5dcmkktt79ddc}”;

      int result = 0;

      for(int i = 0; i = ‘0’ && s1.charAt(i) = ‘0’ && s1.charAt(sub) <= '9') {
      sub++;
      }
      //System.out.println(Integer.parseInt(s1.substring(i, sub)));
      result += Integer.parseInt(s1.substring(i, sub));
      i = sub;
      }
      }

      System.out.println(result);
      }

    • int sum = 0;
      String s = “abcdefghj197scggg5dcmkktt79ddc”;
      String[] sarr = s.split(“[a-z]”);
      for (String s1 : sarr) {
      if (s1.matches(“.*[0-9].*”)) {
      int i = Integer.parseInt(s1);
      sum =sum +i;

      }
      }
      System.out.println(sum);

  5. Find two LOWEST elements who’s sum is 5 from the give array
    int arr[]={0,4,2,1,5,3}

    output should be:- 2 and 3

    • package Solve;

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

      int a[]={0,4,2,1,5,3};
      int sum=5;
      for(int i=0; i<a.length; i++)
      {
      for(int j=i+1; j<a.length; j++)
      {
      if(a[i]+a[j]==sum && a[i]==2 && a[j]==3 )
      {
      System.out.println(a[i]+","+a[j]);
      }
      }
      }

      }

      }

  6. package Solve; /* i hope u will be satisfied with this code and sorry for anything wrong in that code becouse iam just before 2 months start coding */

    public class Mail_Qsns {

    public static void main(String[] args) {

    //Input [4,12,8,34,135]
    //Output [4,8,12,135,34]
    int a[]= {4,12,8,34,135};
    int mid=a.length/2;
    int count=0;
    for(int i=1; i<=mid; i++)
    {
    for(int j=i+1; ja[j])
    {
    int c=a[i];
    a[i]=a[j];
    a[j]=c;
    for(int i1=a.length-2; i1<a.length; i1++)
    {
    for(int j1=i1+1; j1<a.length; j1++)
    {
    if(a[i1]<a[j1])
    {
    int d=a[i1];
    a[i1]=a[j1];
    a[j1]=d;
    }
    }
    }
    }
    }
    }
    for(int i=0; i<a.length; i++)
    {
    System.out.print(a[i]+" ");
    }

    }

    }

Leave a Reply