0

I have checked in many sites but didn't get proper answer.Can any one please tell me the answer.

Riz
  • 29
  • 7
  • 2
    What happens when you try? – JB Nizet Jun 23 '17 at 06:12
  • You mean the String[] args that's usually found as a parameter in the main method? If so, it may have been answered here [What is “String args[]”? parameter in main method Java](https://stackoverflow.com/questions/890966/what-is-string-args-parameter-in-main-method-java) – Andrés Avila Wille Jun 23 '17 at 06:15

3 Answers3

2

They are mandatory as they make up part of the method signature, without them java does not recognize the method as the entry point.

The parameters are read whenever you decide to read / use them, they don't need to be read unless you need them.

They are filled when the program is invoked from the command line, they are the command line arguments.

Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
1

to clarify:

Are string parameters mandatory in main method in java?

in the signature of the method yes, the main method must look like

public static void main(String args[]) {

and if you modify that then the method will never be recognized as an entrance point to the app, example:

public static void main( ) {

and you will get an error complaining about missing main method...

on the other hand, doing this

public static void main(String args[]) {

doesnt mean you need to start the application with string forcibly, you can actually pass none of the parameters meaning that the array args has no elements

At what time are the parameters read?

as soon as you are inside of the main method...

you can do:

public static void main(String args[]) {
    System.out.println(args.length);

so you will get a 0 if you dont pass any parameter, or n is you pass n paramteres (this is tricky if you are comming from other languages like C++ or Python where the name of the app is considered the parameter at index 0, dont let them fool you :) )

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

The String...args parameter in the main method is a varargs.

It will represent all the parameters you give when you run the Java application. args is indeed an array of String (String[]). If you give no parameter, the array is empty.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35