aspose file tools*
The moose likes Beginning Java and the fly likes Why we pass string object to main? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why we pass string object to main?" Watch "Why we pass string object to main?" New topic
Author

Why we pass string object to main?

Anuj Prashar
Ranch Hand

Joined: Apr 15, 2008
Posts: 99

Hi..
What is exact reason for which we pass main method string object

public static void main(String [] args)

Thankyou


SCJP 5,SCWCD 5, RHCT
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

They represent any parameters passed to the Java application when it was run.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
f. nikita thomas
Ranch Hand

Joined: Mar 02, 2008
Posts: 87
imagine you invoke your java program on the commandline:

# java someClass report.txt out.txt

someClass----->your compiled source file minus the .java
report.txt---->[0] of the String[] args
out.txt------->[1] of the String[] args

the arguments are the missing pieces of the program. if you use them in your code and don't present them on the commandline you'll get an
ArrayIndexOutOfBoundsException. take care
[ April 15, 2008: Message edited by: f. nikita thomas ]

Imagination is more important than knowledge "Albert Einstein"
Anuj Prashar
Ranch Hand

Joined: Apr 15, 2008
Posts: 99

Thanks for reply....

But if we use empty parenthesis like-
class MyProg {
public static void main(){
}
}
and does not pass any arguement on command line
like--
java MyProg

why I get message - Exception in thread "main" java.lang.NoSuchMethodError:main

Why exception is there, I'm using no parameter in main method so there is no need of passing arguement to it.
Please clear my doubt.
Thanks
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

Because it's just the rule in Java unlike in some other languages, C/C++/C#


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Anuj Prashar
Ranch Hand

Joined: Apr 15, 2008
Posts: 99

Thanks for reply Mr. Wong.

Can you elaborate more on that rule
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

In java, the main method must have String[] as its argument. Even if you don't pass any arguments from the comamnd line, you still need it.
S Reddy
Ranch Hand

Joined: May 17, 2007
Posts: 45
It is a rule in Java that you have to allow to send Array of String object to main, whether you will pass parameters at run time or not. Even you don't have any need to send parameters through command line you must write main method like

public static void main(String[] a)

you can use any identifier name in the place of a.
Anuj Prashar
Ranch Hand

Joined: Apr 15, 2008
Posts: 99

Thanks for replying
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why we pass string object to main?