*
The moose likes Cattle Drive and the fly likes Command Line Arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "Command Line Arguments" Watch "Command Line Arguments" New topic
Author

Command Line Arguments

Betty Reynolds
Ranch Hand

Joined: Feb 16, 2000
Posts: 111
I found it very confusing that the command line arguments do not appear to follow the rules for strings. For example,
args.length() is not valid. I believe this would be valid for a string declared as a variable.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Command line arguments follow the rules for an array of Strings, because that's what they are. An array has a length field and not a length() method, while a String has a length() method but not a length field. (Why this is I don't know, but we're stuck with it.) Assuming you've declared you main method thus:
<code><pre> public static void main(String[] args) {</pre></code>
...then args refers to the whole array, and args[0] refers to the first element in the array, which is a String. So, if you want to know how many command-line arguments there are, use args.length. To find the length of the first argument (assuming it exists), use args[0].length(). Make sense?

"I'm not back." - Bill Harding, Twister
Betty Reynolds
Ranch Hand

Joined: Feb 16, 2000
Posts: 111
Thanks again Jim. Your clarifications are extremely helpful.
Mark Whelchel
Greenhorn

Joined: Apr 24, 2000
Posts: 2
Which is the preferred syntax?
String[] args
or
String args[]
JJ2 seems to switch freely between the two styles.

[This message has been edited by Mark Whelchel (edited April 28, 2000).]
[This message has been edited by Mark Whelchel (edited April 28, 2000).]
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20494
    ∞

I prefer String[] args. I think it is simpler.


permaculture Wood Burning Stoves 2.0 - 4-DVD set
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Command Line Arguments
 
Similar Threads
how to read character from command line and store it string
command line arguments
Assertion issue
Security Policy File
Head First - MiniMiniMusicCmdLine