Java how to find max / min in an array

Java how to find max / min in an array

To find the maximum and minimum values in an array in Java, you can use a loop to iterate over the array and compare the values to the current maximum and minimum.

Here's an example of how to find the maximum and minimum values in an array in Java:

r‮efe‬r to:lautturi.com
int[] numbers = {1, 2, 3, 4, 5};

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;

for (int number : numbers) {
  if (number > max) {
    max = number;
  }
  if (number < min) {
    min = number;
  }
}

System.out.println("The maximum value is " + max);
System.out.println("The minimum value is " + min);

In the above example, an array of integers is created with five elements. The max variable is initialized to the minimum value of an int (Integer.MIN_VALUE) and the min variable is initialized to the maximum value of an int (Integer.MAX_VALUE).

A for-each loop is then used to iterate over the array and check if each value is greater than the current max or less than the current min. If it is, the value is stored in the max or min variable, respectively.

After the loop completes, the max and min variables will contain the maximum and minimum values of the array, respectively. These values are then printed to the console.

Keep in mind that this example only works for arrays of integers. If you are working with an array of a different data type, you may need to use a different approach to find the maximum and minimum values. For example, you could use the Collections.max() and Collections.min() methods to find the maximum and minimum values of an array of objects that implement the Comparable interface.

Created Time:2017-11-03 23:27:08  Author:lautturi