There are two main ways to find the minimum and maximum element in an array using Java:
1. Using a loop:
This approach iterates through the array, comparing each element with a variable holding the current minimum or maximum value.
public class MinMax { public static void main(String[] args) { int[] numbers = {23, 92, 56, 39, 93}; int min = numbers[0]; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < min) { min = numbers[i]; } if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Minimum: " + min); System.out.println("Maximum: " + max); } }
2. Using `Math.min` and `Math.max` (for primitive arrays):
For primitive arrays (e.g., `int[]`, `double[]`), you can use the `Math.min` and `Math.max` methods, which take two or more values as arguments and return the smallest or largest, respectively.
public class MinMax { public static void main(String[] args) { int[] numbers = {23, 92, 56, 39, 93}; int min = Math.min(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]); int max = Math.max(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]); System.out.println("Minimum: " + min); System.out.println("Maximum: " + max); } }
Both methods achieve the same result. The first approach is more versatile and can be adapted to work with different types of arrays with custom comparison logic. The second approach is concise and efficient for primitive arrays, but it assumes the elements can be directly compared using the comparison operators.