Home » Online Computer Education » Learn Fundamentals of Java Programming “Array Manipulation in Java Programming ” Lesson 24

Learn Fundamentals of Java Programming “Array Manipulation in Java Programming ” Lesson 24

Array Manipulation

In the previous section you learned about some useful prebuilt classes for data input. In this section, we will explore the prebuilt Arrays class from the java.util package for array handling. The Array class has a number of useful methods. Let’s start by using the sort() method to sort an array of integers in ascending order.

First we import java.util.Arrays class. Then in the main() method, we just call the Arrays.sort() method on the array we need to sort.

double[] marks = {346, 144, 103, 256.5, 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(ma rks[ marks. length -1]);

The same method can be used to sort an array of Strings in alphabetic order.

String[] names =
{“Sleepy”,”Doc”,”Happy”,”Grumpy”,”Bashful”,”Dopey”,”Sneezy”};
Arrays.sort(names );

Java fundamentals array 15

Figures 1.9d and 1.9e show the Array Sort Demo program and its output respectively.
The binarySearch() method of the Arrays class helps us search for a specific element in the array. The parameters it needs are the array to be searched and the key element to be searched. The method returns the index of the array where the key is present. If the key is not found in the array, the binarySearch method returns -1.

double[] marks = {346, 144, 103, 256.5, 387.5};
int key = 256.5;
int index = Arrays.binarySearch(marks,key);

Java fundamentals array 16

Figures 1.9e and 1.9f show the Array Search Demo program and its output respectively.

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

Your email address will not be published.