How to find largest and Smallest number in Array

HQ ┬╗ Java Tutorial ┬╗ Example Source Code ┬╗ Java Array Examples ┬╗ How to find largest and Smallest number in Array
How to find largest and Smallest number in Array 2015-04-14T12:31:42+00:00

There are multiple solutions on how to find the smallest and largest number inside an array. We would be showing two ways, one which uses several methods readily available on the API. And the other which rely on basic usage of operators and loops.

Use of Sort to Identify Smallest and Largest Number in an Array

This method simply leveraged the existing functionality of the static method Arrays.sort. This method sort the specified array. The sort method arrange the elements from highest to lowest. So the first element of the resulting array would be our largest number while the last element would be the smallest. Lets take a look for below example

Sample Output:

Use of loops and Operators to find the smallest and largest number in an array

For this example in order to find the smallest and largest number, we have initially assigned a variable greatestNumber and  smallestNumber the first value of the array. And then we just use the operator < and > to check if the next number is less than or greater than the current value. From the result of the checking we change the value of the two variables.

Sample Output:

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close