get maximum value in array java code example

Example 1: max in array java

// Initializing array of integers 
        Integer[] num = { 2, 4, 7, 5, 9 }; 
// using Collections.min() to find minimum element 
        // using only 1 line. 
        int min = Collections.min(Arrays.asList(num)); 
  
        // using Collections.max() to find maximum element 
        // using only 1 line. 
        int max = Collections.max(Arrays.asList(num));

Example 2: Java program to find maximum and minimum number without using array

// Java program to find maximum and minimum number without using array
import java.util.Scanner;
public class MaximumMinimumWithoutArray
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter total number: ");
      int numbers = sc.nextInt();
      int maximum = Integer.MIN_VALUE;
      int minimum = Integer.MAX_VALUE;
      System.out.println("Please enter " + numbers + " numbers.");
      for(int a = 0; a < numbers; a++)
      {
         int current = sc.nextInt();
         if(current > maximum)
         {
            maximum = current;
         }
         if(current < minimum)
         {
            minimum = current;
         }
      }
      System.out.println("largest of " + numbers + " numbers is: " + maximum);
      System.out.println("smallest of " + numbers + " numbers is: " + minimum);
      sc.close();
   }
}

Example 3: java max array

public static String max(String[] arr) {
  String result = arr[0];
  for (int i = 1; i < arr.length; ++i) {
    if (result.compareTo(arr[i]) < 0) result = arr[i];
  }
  return result;
}

Example 4: how to get the max value of an array java

public static double arrayMax(double[] arr) {
    double max = Double.NEGATIVE_INFINITY;

    for(double cur: arr)
        max = Math.max(max, cur);

    return max;
}

Example 5: java max array

public static double max(double[] arr) {
  double result = Double.NEGATIVE_INFINITY;
  for (int i = 0; i < arr.length; ++i) {
    if (result < arr[i]) result = arr[i];
  }
  return result;
}