This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between (String... args) vs (String[] args)

 
Rahul mir
Ranch Hand
Posts: 38
Eclipse IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please someone explain difference between

public static void main(String[] args) vs public static void main(String... args).
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String... style was a bit of syntactic sugar introduced in Java 5, and it allows you to call methods with a variable number of arguments:


That gets converted behind the scenes into a method callThis(int[] values), so within the method values is an array.

As a result, the two examples you give get compiled to exactly the same method, which is why you're allowed to use either. It would only make a difference if you wanted to call the main() method from your own code, but you shouldn't really be doing that very often.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33696
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:As a result, the two examples you give get compiled to exactly the same method, which is why you're allowed to use either. It would only make a difference if you wanted to call the main() method from your own code, but you shouldn't really be doing that very often.

I do that when writing end to end unit tests for standalone programs. I like the String... style for that because it is easier to write the tests.
 
Paul Clapham
Sheriff
Pie
Posts: 20188
26
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One difference is that the String... parameter can only be the last parameter in the declaration of the method. So, valid code:



and invalid code:



This is to make the handling of varargs (yes, really, that's the name of this feature) less of a nightmare for compiler-writers. Tutorial here: Varargs.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic