aspose file tools*
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
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: 14435
    
  23

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 8 API documentation
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  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)