Java - Varargs method to get the max value

Description

Varargs method to get the max value

Demo

public class Main {
  public static int max(int... num) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < num.length; i++) {
      if (num[i] > max) {
        max = num[i];/*ww  w.jav a 2s .  co  m*/
      }
    }
    return max;
  }

  public static void main(String[] args) {
    int max1 = max(1, 2);
    int max2 = max(1, 2, 3);
    System.out.println(max1);
    System.out.println(max2);
  }
}

Result

You can rewrite the code for max() method using foreach loop as follows:

Demo

public class Main {
  public static int max(int... num) {
    int max = Integer.MIN_VALUE;
    for (int currentNumber : num) {
      if (currentNumber > max) {
        max = currentNumber;/* w  ww. j a v a2 s .c  om*/
      }
    }
    return max;
  }

  public static void main(String[] args) {
    int max1 = max(1, 2);
    int max2 = max(1, 2, 3);
    System.out.println(max1);
    System.out.println(max2);
  }
}

Result

Related Topic