• 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
  • 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: 4566
8
  • Likes 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: 34218
341
Eclipse IDE Java VI Editor
  • 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
Posts: 20983
31
Eclipse IDE Firefox Browser MySQL Database
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic