Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

main(String[]args)

 
Oceana Wickramasinghe
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15274
38
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Oceana Wickramasinghe
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic