| Author |
what is the difference between these.... String[] String... String
|
Srikanthh Ar
Greenhorn
Joined: Jul 14, 2009
Posts: 18
|
|
can anyone explain me what is the difference between these.... String[] String... String
when used in the method arguments.
example:
foo(String... args)
foo(String[] args)
foo(String args)
when all these 3 used which method called first... and why..
its very confusing.. pl explain with an example...
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
foo(String... args) is called when you provide zero or more Strings, or a String array.
foo(String[] args) is called when you provide a real String array.
foo(String args) is called when you provide exactly one String.
That leaves two overlaps: one String and a String array. For these cases, the most specific method is found. Applied to varargs, it says that the method with varargs is only used if no other method matches.
So:
That compiler error is thrown because null matches both String and String[], and the compiler can't make a choice between the two. It will work when you either provide a reference variable that happens to be null, because it then uses the variable's declared type, or if you manually cast and tell the compiler which of the two methods to use.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Srika,
Welcome to JavaRanch! The 'String...' form represents a vararg, which means that the method expects zero or more Strings to be passed to it. The 'String[]' form represents a String array, so the method expects a String array to be passed to it. The 'String' form represents a String object, so the method will be expecting a single String object to be passed to it.
John.
[Edit: looks like Rob got to this first ]
|
 |
Sean Clark
Rancher
Joined: Jul 15, 2009
Posts: 377
|
|
srika ar wrote:foo(String... args)
This is a new one which I think was added fairly and is a variable length list, so in your example 'args' would be a List of strings.
or
Not sure if they can have 0 args though.
srika ar wrote:foo(String[] args)
This method would accept an array so...
srika ar wrote:foo(String args);
This is the simple one, the method accepts a single String argument
Hope that helps
Rob's answer is better!
|
I love this place!
|
 |
Srikanthh Ar
Greenhorn
Joined: Jul 14, 2009
Posts: 18
|
|
thank you very much... rob ,john and clark
i am clear in this now...
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: what is the difference between these.... String[] String... String
|
|
|