• Post Reply Bookmark Topic Watch Topic
  • New Topic

(String[] args) - What is the use of this?  RSS feed

 
Bennett Nelson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! I am an absolute noob at java and really programming in general, but I am trying to learn through the book "Head First Java." Everything is very clear so far except for in the main method. It has me type this in for the main method:

public static void main(String[] args)

Everything makes sense to me except for the (String[] args) part. The book says it is because the method must be given an array of strings and this array is called args. But why? Because I don't remember having to give it any strings at any point. Maybe I just misunderstood. If someone could please clear this up for me, it would be much appreciated. Thanks!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bennett,
Welcome to CodeRanch!

Passing arguments to a program is optional so you probably haven't encountered it yet. If you just call "java Foo" - args is an empty array because there are no arguments. If you call "java Foo a", args will contain one String - "a".
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also read the Java tutorial page on this http://docs.oracle.com/javase/tutorial/getStarted/application/

The book says it is because the method must be given an array of strings and this array is called args

The main method must have a single argument which is an array of type String but the argument can be called anything want, it's just common practice to call it args.
 
Bennett Nelson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh ok! So they don't have to be used. They are just for modifying the way your program runs right? Thanks for the help!
 
Tony Docherty
Bartender
Posts: 3271
82
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bennett Nelson wrote:Oh ok! So they don't have to be used. They are just for modifying the way your program runs right? Thanks for the help!

Yes you don't need to use args unless your program handles command line arguements and like Jeanne said if there are no command line arguments used when you start the application then the args array is an empty array. for example:

If you compile above code and then run it as follows:

java ToUpperCase

you get and output of:

There are no command line args to convert to upper case

Whereas if you run it as follows:

java ToUpperCase test susan text

you get an output of:

Arg 1 = TEST
Arg 2 = SUSAN
Arg 3 = TEXT
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!