The following program shows how to Find the Maximum and Minimum in an Array in Java.
At first, we declare and initialize a one-dimensional integer array. After that, we start a for loop that traverses all array elements one by one. Within the same loop, we determine both the maximum and minimum. Then we display these values.
public class Exercise2
{
public static void main(String[] args) {
int[] myarray={3, 5, 1, 12, 9, 24, 6, 8};
int maximum=myarray[0], minimum=myarray[0];
System.out.println("Array Elements...");
for(int i=0;i<myarray.length;i++)
{
System.out.print(myarray[i]+"\t");
if(maximum<myarray[i]) maximum=myarray[i];
if(minimum>myarray[i]) minimum=myarray[i];
}
System.out.println("\nMaximum = "+maximum+"\nMinimum = "+minimum);
}
}
Output