Java Arrays - Practice Programs with Solutions


 /////////////////////  SINGLE DIMENSIONAL ARRAYS - SOLUTIONS ////////////////



// 1. Find the Largest Element in an Array


public class LargestElement {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int largest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] > largest) {

                largest = numbers[i];

            }

        }

        System.out.println("Largest Element: " + largest);

    }

}



// 2. Find the Smallest Element in an Array


public class SmallestElement {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int smallest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] < smallest) {

                smallest = numbers[i];

            }

        }

        System.out.println("Smallest Element: " + smallest);

    }

}


//3. Calculate the Sum of All Elements in an Array


public class ArraySum {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        System.out.println("Sum of Elements: " + sum);

    }

}



//4. Calculate the Average of All Elements in an Array


public class ArrayAverage {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        double average = (double) sum / numbers.length;

        System.out.println("Average of Elements: " + average);

    }

}



//5. Reverse an Array


public class ReverseArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int[] reversed = new int[numbers.length];

        for (int i = 0; i < numbers.length; i++) {

            reversed[i] = numbers[numbers.length - 1 - i];

        }

        System.out.print("Reversed Array: ");

        for (int number : reversed) {

            System.out.print(number + " ");

        }

    }

}


//6. Check if an Array Contains a Specific Element


public class ElementSearch {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int target = 7;

        boolean found = false;

        for (int number : numbers) {

            if (number == target) {

                found = true;

                break;

            }

        }

        System.out.println("Element " + target + " found: " + found);

    }

}



//7. Count the Occurrences of a Specific Element


public class ElementCount {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 2, 9, 2};

        int target = 2;

        int count = 0;

        for (int number : numbers) {

            if (number == target) {

                count++;

            }

        }

        System.out.println("Element " + target + " occurs " + count + " times.");

    }

}



//8. Remove Duplicates from an Array


import java.util.Arrays;


public class RemoveDuplicates {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 2, 9, 4};

        int n = numbers.length;

        Arrays.sort(numbers);

        int[] result = new int[n];

        int j = 0;

        for (int i = 0; i < n - 1; i++) {

            if (numbers[i] != numbers[i + 1]) {

                result[j++] = numbers[i];

            }

        }

        result[j++] = numbers[n - 1];

        System.out.print("Array without duplicates: ");

        for (int i = 0; i < j; i++) {

            System.out.print(result[i] + " ");

        }

    }

}


//9. Find the Index of a Specific Element


public class FindIndex {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int target = 7;

        int index = -1;

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == target) {

                index = i;

                break;

            }

        }

        System.out.println("Index of " + target + ": " + index);

    }

}


//10. Print Array Elements in a Single Line


public class PrintArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        System.out.print("Array elements: ");

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}



//11. Copy an Array


import java.util.Arrays;


public class CopyArray {

    public static void main(String[] args) {

        int[] original = {4, 2, 7, 1, 9};

        int[] copy = Arrays.copyOf(original, original.length);

        System.out.print("Copied Array: ");

        for (int number : copy) {

            System.out.print(number + " ");

        }

    }

}


//12. Sort an Array in Ascending Order


import java.util.Arrays;


public class SortArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        Arrays.sort(numbers);

        System.out.print("Sorted Array: ");

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}



//13. Find the Sum of Even Numbers in an Array


public class SumEvenNumbers {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            if (number % 2 == 0) {

                sum += number;

            }

        }

        System.out.println("Sum of Even Numbers: " + sum);

    }

}



/////////////////////  TWO DIMENSIONAL ARRAYS - SOLUTIONS ////////////////


//1. Print a Two-Dimensional Array


public class Print2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        System.out.println("Two-Dimensional Array:");

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                System.out.print(array[i][j] + " ");

            }

            System.out.println();

        }

    }

}


//2. Find the Sum of All Elements in a Two-Dimensional Array


public class Sum2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        int sum = 0;

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                sum += array[i][j];

            }

        }

        System.out.println("Sum of All Elements: " + sum);

    }

}


//3. Find the Maximum Element in a Two-Dimensional Array


public class MaxElement2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        int max = array[0][0];

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                if (array[i][j] > max) {

                    max = array[i][j];

                }

            }

        }

        System.out.println("Maximum Element: " + max);

    }

}


 Object type array


public class ObjectTypeArray {


public static void main(String[] args) {

Object[] a = new Object[5];

      

        a[0] = "Hello";      // String

        a[1] = 123;          // Integer

        a[2] = 45.67;        // Double

        a[3] = true;         // Boolean

        a[4] = 'A';          // Character


       //access specific value from array

       System.out.println(a[2]); //45.67

       System.out.println(a[2].getClass().getSimpleName()); //Double type of object

              

       System.out.println("Reading data from the array using for loop:");

        for (int i = 0; i < a.length; i++) {

             System.out.println(a[i]);

        }

System.out.println("Reading data from the Object array using for-each loop:");

        for (Object element : a) {

           System.out.println(element);

        }

}

}


Sorting array


import java.util.Arrays;

import java.util.Collections;


public class SortArray {

    public static void main(String[] args) {

        

    //Sorting numbers  - ascending order

    int numbers[] = {4, 2, 7, 1, 9};

        

    System.out.println("Before sorting:"+ Arrays.toString(numbers)); //printing array without loop

        Arrays.sort(numbers);

        System.out.println("After sorting:" +Arrays.toString(numbers));

        

        

        //Sorting strings - - ascending order

        String names[]= {"Smith","John","David","Scott"};

        System.out.println("Before sorting:"+ Arrays.toString(names)); 

        Arrays.sort(names);

        System.out.println("After sorting:" +Arrays.toString(names));

        

        

        //Sorting numbers or strings - descending order

        Integer ids[]= {100,500,200,400,600,300};

        

        System.out.println("Before sorting:" +Arrays.toString(ids));

        Arrays.sort(ids, Collections.reverseOrder());

        System.out.println("After sorting in Ascending order:"+ Arrays.toString(ids));

    }

}


Searching element in an array


import java.util.Arrays;


public class SearchElementinArray {


public static void main(String[] args) {

//Linear Search (Works on Unsorted Arrays)

int[] numbers = {5, 3, 8, 1, 2};

        int searchElement = 8;

        boolean found = false;

        

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == searchElement) {

                found = true;

                System.out.println("Element " + searchElement + " found at index " + i);

                break;

            }

        }

        

        if (found==false) {

            System.out.println("Element " + searchElement + " not found in the array.");

        }

        

      //Binary Search (Works on Sorted Arrays)

//If the array is unsorted, you should sort it using Arrays.sort() before performing a binary search.

int[] numbers = {1, 2, 3, 5, 8};  // Array must be sorted

     int searchElement = 3;

        

     int index = Arrays.binarySearch(numbers, searchElement); //method returns the index of the target element if found. If not found, it returns a negative value.

        

      if (index >= 0) {

            System.out.println("Element " + searchElement + " found at index " + index);

        } else {

            System.out.println("Element " + searchElement + " not found in the array.");

        }


}


}



Copying an array


import java.util.Arrays;


public class CopyArrayExample {

    public static void main(String[] args) {

        

        // Original array

        int originalArray[] = {1, 2, 3, 4, 5};

        

        // Method 1: Using a loop

        int copiedArray[] = new int[originalArray.length];

        for (int i = 0; i < originalArray.length; i++) {

            copiedArray[i] = originalArray[i];

        }

       

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        

        

        // Method 2: Using Arrays.copyOf()

        /*int copiedArray[] = Arrays.copyOf(originalArray, originalArray.length);

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

        

        // Method 3: Using System.arraycopy()

        /*int copiedArray[] = new int[originalArray.length];

        System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);

        

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

        

        // Method 4: Using clone()

        /*int copiedArray[] = originalArray.clone();

        

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

    }

}


Equality of arrays



import java.util.Arrays;


public class ArrayEqualityExample {

    public static void main(String[] args) {

        

        int[] array1 = {1, 2, 3, 4, 5};

        int[] array2 = {1, 2, 3, 4, 5};

        //int[] array2 = {5, 4, 3, 2, 1};

        

        // Method 1: Using Arrays.equals()

        //boolean result = Arrays.equals(array1, array2);

        //System.out.println("Are array1 and array2 equal ? " + result);

        

        

        // Method 2: Using a loop 

        boolean result = true;

   

        if (array1.length != array2.length) 

        {

        result = false;

        } 

        else 

        {

        for (int i = 0; i < array1.length; i++) 

        {

                if (array1[i] != array2[i]) 

                {

                    result = false;

                    break;

                }

            }

        }

        

        System.out.println("Are array1 and array2 equal? " + result);

    }

}





Followers