Java - Varargs method with Zero parameter

Introduction

You can use zero or more arguments for a variable-length argument in a method.

The following code is a valid call to the max() method:

int max = max(); // Passing no argument is ok

Demo

public class Main {
  public static int max(int... num) {
    int max = Integer.MIN_VALUE;
    for (int currentNumber : num) {
      if (currentNumber > max) {
        max = currentNumber;//from  ww w.j  av  a 2 s.c  o  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);
    
    int max3 = max();
    System.out.println(max3);
  }
}

Result

The following max() method will force its caller to pass at least two integers:

// Argumenets n1 and n2 are mandatory
int max(int n1, int n2, int... num) {
   // Code goes here
}

Demo

public class Main {
  public static int max(int n1, int n2, int... num) {
    // Initialize max to the maximum of n1 and n2
    int max = (n1 > n2 ? n1 : n2);

    for (int i = 0; i < num.length; i++) {
      if (num[i] > max) {
        max = num[i];/*from  w w  w .  j  a v  a  2s. com*/
      }
    }
    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);

    //max();   // A compile-time error
    //max(10); // A compile-time error

  }
}

Result

Related Topic