# JAVA gets a simple instance of the maximum and minimum values in an array

• 2020-04-01 03:26:59
• OfStack

Today this article shares with you an example of how to get the maximum and minimum values in an array. Good for Java beginners to review the basic use of arrays and flow control statements. The details are as follows:

This program is mainly to find the maximum and minimum values in the array

``````
public class TestJava4_3
{
public static void main(String args[])
{
int i,min,max;
int A[]={74,48,30,17,62};  //Declares the integer array A and assigns an initial value

min=max=A[0];
System.out.print(" An array of A Are: ");
for(i=0;i<A.length;i++)
{
System.out.print(A[i]+" ");
if(A[i]>max)   //Judgment maximum
max=A[i];
if(A[i]<min)   //Judgment minimum
min=A[i];
}
System.out.println("n The maximum value of the array is: "+max); //Output maximum
System.out.println(" The minimum value of the array is: "+min); //Output minimum
}
}

``````

Output result of the program:

``````
An array of A Are: 74 48 30 17 62
The maximum value of the array is: 74
The minimum value of the array is: 17

``````

Program description is as follows:

1. Line 6 declares the integer variable I as the index of the loop control variable and the array: in addition, it also declares the variable min with the minimum value and Max with the maximum value.
2. Line 7 declares the integer array A, which has five elements with values of 74, 48, 30, 17, and 62.
3. The initial values of min and Max in line 9 are set as the first element of the array.
Line 10-18 outputs the contents of the array one by one, and determines the maximum and minimum values of the array.
5. Output the maximum and minimum values after the comparison in lines 19 to 20. After the initial values of the variables min and Max are set as the first element of the array, they are compared with each element in the array one by one. If it is smaller than min, the value of this element is assigned to min to store, so that the content of min can be kept to a minimum. Similarly, when the element is larger than Max, the value of the element is assigned to Max to keep the contents of Max at a maximum. When the for loop is completed, it means that all elements in the array have been compared. At this time, the contents of the variables min and Max are the minimum and maximum values.