-3

In the Java Programming when we pass the all arguments from the varargs then how can i dispaly that argument value.. For example i saw a program something like this :

class var{
   static void dis (int...num) {
      System.out.println ("Number of Arguments = " + num.length);
      for (int x : num)
      System.out.println(x + " ");
   }

   public static void main (String args[]) {
      dis();
      dis(1, 2, 4, 6, 8, 10);
      dis(12, 14, 16, 18, 20);
   }    
}

In the above program what action is performing by for(int x : num) .

Manohar Kumar
  • 605
  • 9
  • 12

3 Answers3

2

varargs is just a syntactic sugar on top of getting an array argument - and you can still treat it as such. E.g.:

static void dis (int... num) {
  // num is actually an int[]
  System.out.println (Arrays.toString(num));
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

In Java the varargs are simply an array.

In the case you've shown: num is int[] num.

By the same principle you could declare your main method as:

public static void main(String... args)

They're equivalent.

According to the Oracle docs:

the varargs feature automates and hides the process of passing an array to a method.

Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
0

for(int x : num) is an "enhanced for loop". It means that x takes each value in num in turn and the loop is executed with that value. It's just syntactic sugar on an ordinary for loop.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38