Varargs method to get the max value
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];//from w w w . ja va 2 s .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); } }
You can rewrite the code for max() method using foreach loop as follows:
public class Main { public static int max(int... num) { int max = Integer.MIN_VALUE; for (int currentNumber : num) { if (currentNumber > max) { max = currentNumber;// ww w. ja v a2s.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); } }