Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multiple arguments dot notation - Varargs

Tags:

java

constants

I've just acknowledged dot notation for method declaration with multiple arguments
like this:

public function getURLs(URL... urls){     for(int i = 0; i < urls.length; i++){         // walk through array of arguments     } } 

And using like this

getURLs(url1, url2, url3); 

where those method arguments are converted implicitly into URL[] urls

  1. Did I understand its behavior properly?
  2. Where is documentation to this syntax?
  3. From which version of JRE (J2ME,J2SE,Dalvik) is this supported?
like image 836
Marek Sebera Avatar asked Sep 24 '11 12:09

Marek Sebera


People also ask

What is the rule for using varargs in Java?

While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.

How do you pass multiple arguments in Java?

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Is it good to use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

How many number of values can be accommodated by Varargs in Java?

A method (including the static class initializer) can have at most 64k. If the arguments are such that they can be pushed with a single bytecode that is 1 byte long each, you can have something about 64000 arguments on a call.


1 Answers

Yes, that is how it works. The arguments are automatically put into an array. The argument "urls" behaves like a URL[]. Varargs are documented here. They were introduced in Java 1.5, so, are available in J2SE 1.5+, and all of Android since it supports Java 1.5+ language features. No version of JavaME/J2ME supports it.

like image 89
Sean Owen Avatar answered Oct 10 '22 18:10

Sean Owen