Page 246 - IT-802_class_12
P. 246

Notes

                    That,  since  assertions  reduce  runtime  performance,  they  are  disabled  by  default.  To  enable
                    assertions  at  runtime,  you  can  enable  them  from  the  command  line  by  using  the  –ea  option
                    java –eaAssertionDemo


          3.7 arraY manIPuLatIon

        An array is a collection of values of a similar type. In other words, an array is a group of variables accessed through a
        common name. It can store a number of values of any primitive or non-primitive type. It is a composite data type. The
        values stored in an array are known as array elements. In an array, the values are stored in an ordered manner and each
        value has an index starting from 0 which means that the first value is stored at the 0th index, the second value is stored
        at the 1st index, and so on. For example,
                        Array Values/Elements           5    10    8     7     1     6     4     3    11


                                Index                   0     1    2     3     4     5     6     7     8

        In the above example, you can see that value 5 is stored at 0th index, value 10 is stored at the 1st index, and the last
        value 11 is stored at the 8th index. The number of elements specifies the length of the array. In the above example,
        there are nine elements in the array, so the length of the array is 9.

        There are several helpful methods in the Arrays class. Let’s begin by sorting an array of integers in ascending order
        using the sort()method.
        We import the java.util.Arrays class first. The array we need to sort is then given to the Arrays.sort() method in the
        main() method.

        double[] marks = {103, 144, 256.5, 346, 387.5} ;
        Arrays.sort(marks);
        The marks array after sorting becomes =

        {103.0, 144.0, 256.5, 346.0, 387.5}.
        Sorting makes it easier for us to find the lowest and highest marks obtained by a student.
        To print the lowest marks, we can now write System.out.println(marks[0]);

        To print the highest marks,we can write System.out.println(marks[marks.length-1]);
        The same method can be used to sort an array of Strings in alphabetic order.

        String[] names = {“Sarthk”,”Saumya”, ”mayank”,”mudit”,”Shiva”,”Anju”, “Savita”};
        Arrays.sort(names);
        Given below is a program to search a number in an array. Where:

        double[] marks = {123, 651, 201, 854, 745};
        int key = user input;
        int index = Arrays.binarySearch(marks,key);











          244   Touchpad Information Technology-XII
   241   242   243   244   245   246   247   248   249   250   251