The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Arguments in main

Posted by Boon on February 14, 2001 at 8:08 PM

Hi,

Below mentioned that u can pass some parameters to the class.
So, how do we declare if we instantiate an object of the class.

Eg. C1 has 2 strings parameter

Public Class C1{

public void main{
C1 var=new C1(param1, param2); // Object Instantiation
}
}

Above Object Instantiation will give error during compilation.

Regards
Boonwah

> When you run your class then you can also pass some parameters to the class you want to run. Since the execution starts in main methods those arguments specified by you at command line are passed to main method. Suppose you type
> java C1
> where C1 is your class you want to run then main method of C1 is called. Since you ddidn't pass any parameter after C1 on command line then JVM will just ccreate an empty string array like
> String[] temp = new String[0] ;
> and then it makes a call like
> C1.main ( temp ) ; // Internally it uses reflection to do this

> If you pass any parameter at command line then
> java C1 param1 param2
> then JVM stores these param1 and param2 in string array passes them to main method of class C1.
> Some language uses a String argument instead of String array and in those cases you have to parse the command line parameters.
> Now your question is why "String[] params" is compulsory in main declaration. Let us take a case when it is not necessary in j ava. In that case you would have to define at least two main methods in a class if you want to run it. One which will be called when you don't pass any parameters and the other when you pass some parameters. And your both main methods would have been identical. To make the programming lilfe easier and to reduce the confusion which main will be called when Java insists to define you a main method with "String[] params" argument and this method will be called when you run your class irrespective of no of parameters you pass.

> Thanx
> Kishori






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us