• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using String... instead of String[]  RSS feed

 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just happened to see my friend using this,

and it works fine, to my surprise!!
I asked him for an explanation, but he was not sure. He just said both are the same n no difference.

Are both 'String...' and String[] the same???
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not exactly. String... is more powerful. It allows arrays like String[], but also lists of arguments. The following is legal with your declaration:
The ... are called varargs; look it up.
 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats cool!

1. So, that limits '...' only to arguments,right?
2. Can this be used with any Object - like func(Integer... ints)?
3. Does '...' work with primitives - int... ?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

And you may want to tell your friend -- if you don't know what something is, is it a good idea to use it? Just because a var-arg can take an array, it doesn't mean that you should use it, when you meant an array.

Henry
 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey...dont bother yourself, Rob. I found my answers! Thanks for your explanation.
For others,

1. Varargs can be used only in the final argument position. Only in arguments.
2. Any Object can be used along with.
3. primitives supported to! - public static void hello(int... a) is fine with the compiler!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinoth Kumar Kannan wrote:1. So, that limits '...' only to arguments,right?

Right, and due to technical reasons it's only allowed once in a method's parameter list, and only as the last parameter.

2. Can this be used with any Object - like func(Integer... ints)?
3. Does '...' work with primitives - int... ?

Why don't you try it out?
 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I did!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!