English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

What is the use of String arguments in main()? why should we use static while defining main() function?

2007-07-10 11:53:52 · 1 answers · asked by anu 1 in Computers & Internet Programming & Design

1 answers

(1) String array in "main(String[] args)" are the command line arguments. So, for example, if you execute your class like this from the command line:

java com.mypackage.MyClass foo bar

... then the String[] argument to main will be an array of two strings, "foo" and "bar". If you don't specify any command-line arguments to java beyond your class name, then the array will be zero-length.

(2) static methods are executed on a class without needing an instance of the class. When the main() method is run, there isn't an instance of the class created. If you want an instance of your class, you can create one (with whatever constructor you want to use) in the main() routine, then call non-static methods on that instance. For example:

public static void main(String[] args) {
if (args.length < 1) throw new RuntimeException( 'Require at least one command-line argument' );
MyClass c = new MyClass(args[0]);
c.someNonStaticMethod();
}

2007-07-10 12:42:48 · answer #1 · answered by McFate 7 · 0 0

fedest.com, questions and answers