Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the difference between these.... String[] String... String

 
Srikanthh Ar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Srikanthh Ar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much... rob ,john and clark

i am clear in this now...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic