File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes difference between (String... args) vs (String[] args) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "difference between (String... args) vs (String[] args)" Watch "difference between (String... args) vs (String[] args)" New topic
Author

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

Rahul mir
Ranch Hand

Joined: Oct 31, 2012
Posts: 38

Hi,
Please someone explain difference between

public static void main(String[] args) vs public static void main(String... args).
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4490
    
    8

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

Joined: May 26, 2003
Posts: 31067
    
232

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
Bartender

Joined: Oct 14, 2005
Posts: 18988
    
    8

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.
 
 
subject: difference between (String... args) vs (String[] args)