This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes main(String[]args) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "main(String[]args)" Watch "main(String[]args)" New topic
Author

main(String[]args)

Oceana Wickramasinghe
Ranch Hand

Joined: Mar 02, 2011
Posts: 77
Hey guys, i want to know exactly what (String[]args) do. I know that we can use (String[]args) to pass command line arguments. But if i just write a simple program like,



and dont pass any command line arguments, does this program use (String[]args) at all?

What purpose does (String[]args) serve other than accepting command line arguments?

Is (String[]args) important for the execution of a program(if you dont use command line arguments)?

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

If you don't pass any arguments on the command line, then args will be an array of length 0. Note that you must always have the String[] args when you specify the main method, because Java expects it that way - it looks for a public static method with the name main that takes a String[] as the argument. It's ofcourse not required that you do anything with the arguments. If you don't use them, then simply nothing happens with them.

It doesn't have any other purpose than passing in command line arguments.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11172
    
  16

it will not be used, but you still have to have it there. The jvm is EXPLICITLY looking for a method with that signiature. So if you wrote

public static void main(){...}

and didn't have the "String [] args", the jvm would not be able to find the 'entry point' into your program, and would complain.

Note that the variable name can be anything, but 'args' is used by convention. I believe the args array will be created as an array with a length of 0, so you can test "if args.length() < 1" and not worry about a NPE.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Oceana Wickramasinghe
Ranch Hand

Joined: Mar 02, 2011
Posts: 77
Thanks everyone
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: main(String[]args)
 
Similar Threads
String args[ ] in main
Command Line Arguments
passing arguments from command line
command line arguments for a file
Qn from Javacert