Back to: Java Tutorials
To find the maximum and minimum value in an array of integers in Java, you can use a for loop to iterate over the array and compare each element to the current maximum and minimum values. Here is an example:
public class MaxMinExample {
public static void main(String[] args) {
int[] numbers = {2, 5, 8, 1, 9, 3};
int max = numbers[0];
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
System.out.println("Maximum value in array: " + max);
System.out.println("Minimum value in array: " + min);
}
}
In this code, we define an array of integers numbers
with values of {2, 5, 8, 1, 9, 3}. We then define two variables max
and min
, initialized to the first element of the array. We use a for loop to iterate over the array, comparing each element to the current max
and min
values. If an element is greater than the current max
, we update max
. If an element is less than the current min
, we update min
. Finally, we print the max
and min
values to the console.
The output of this code is:
Maximum value in array: 9
Minimum value in array: 1
Using built-in Method
To find the maximum and minimum value in an array of integers in Java, you can use the Arrays
class from the java.util
package. Here is an example:
import java.util.Arrays;
public class MaxMinExample {
public static void main(String[] args) {
int[] numbers = {2, 5, 8, 1, 9, 3};
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("Maximum value in array: " + max);
System.out.println("Minimum value in array: " + min);
}
}
Follow us on social media
Follow Author