Java Program to implement ‘Arrays’ and its member functions.

     Array has collection of elements. ‘Arrays’ is a built in class in java package java.util. This class contains many static methods to process array operations.

Some of the methods are listed below.

sort() :This function sorts the array elements.

parrelSort() : Suits for larger array to sort the elements parallel.

equals():It compares two arrays for equality.

binarySearch(): It uses binary Search method to find an element.

fill() :it fills a data for set of elements.

toString(): It converts the array to String

asList():It converts the array to List.

Stream():it is used for Stream operations.

copyOf(): It copys the array elements into another array.

copyOfRange(): it copys the data in the specified range and add to another array.

setAll(): All the elements are set by this method.

An example is given below.

#Java Program to implement ‘Arrays’ and its member functions.

import java.util.Arrays;

import java.util.Scanner;

public class ArrayEg3 {

    public static void main(String[] args) {

        Scanner scanner1 = new Scanner(System.in);

        //get the size of the array

        System.out.print("Please,Enter the size of the array: ");

        int size = scanner1.nextInt();

        // An array with specified size is created here

        int[] sample = new int[size];

        // Read the data elements by for loop

        System.out.println("Enter " + size + " elements:");

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

            sample[i] = scanner1.nextInt();

        }

       // Sort the data elements using sort()

        Arrays.sort(sample);

        System.out.println("Sorted: " + Arrays.toString(sample));

       // binarySearch() method of searching

        int index = Arrays.binarySearch(sample, 7);

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

       // Let us check for equality of two arrays

        int[] anotherArray = {11, 24, 45, 7, 19};

        boolean areEqual = Arrays.equals(sample, anotherArray);

        if(areEqual)

           System.out.println("Arrays are equal");

        else

           System.out.println("Arrays are not equal");

       // Fill the data with a data

        int[] fArray = new int[5];

        Arrays.fill(fArray, 12);

        System.out.println("The array after Filled data: " + Arrays.toString(fArray));

    }

}

Output:

C:\raji\blog>javac ArrayEg3.java

C:\raji\blog>java ArrayEg3

Please,Enter the size of the array: 7

Enter 7 elements:

23

4

67

56

34

98

87

Sorted: [4, 23, 34, 56, 67, 87, 98]

Index of 7: -2

Arrays are not equal

The array after Filled data: [12, 12, 12, 12, 12]

This is the way of using ‘Arrays’ in java. Enjoy Coding!!!!!

No comments:

Post a Comment