1

i am wondering if it is possible to define parameters for a command line program directly in the main function as parameters, like this:

public class HelloWorld {
    public static void main(double a1, double a2) {
        //do something with a1, a2...
    }
}

instead of:

public class HelloWorld {
    public static void main(String[] args) {
        //do something with args[0], args[1]
    }
}
binaryBigInt
  • 1,526
  • 2
  • 18
  • 44

4 Answers4

2

Yep it's possible. You can't create your own parameters tho. The args[] variable can already handle those passed values. You just need to access the value in every command line argument by calling args[0]...args[n].

Example: String option = args[0]; System.out.println(option);

Test: java myProgram.java -sampleArgument

Result: -sampleArgument

2

No, this is not allowed by the Java language specification.

To quote it:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)

public static void main(String... args)

Link: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1

paisanco
  • 4,098
  • 6
  • 27
  • 33
1

I got somes bas new for you... It's not possible directly. The jvm will always search for a method with the following signature as an entry point of your program (I'ts a standart, it will problably never change):

public static void main(String ... args)

I know that the "String ... args" may seems odd but it's just another notation for the "String [] args". However, you can still call them , one after another by doing that:

public static void main(String ... args){
    System.out.println(args[0]);//if there is one argument
}
Reirep
  • 78
  • 7
0

Of course you can define a main method that takes any kind of parameter.

But when you intend to use that main method as "entry point" (by telling the JVM to to invoke the corresponding class), sorry, that will not work.

The JVM only allows you to run a main that is defined as public static void and taking an array of Strings.

But of course, there are many libraries out there that help there: for example by allowing you to "define" expected command line arguments and their type. Meaning: you don't have to constantly re-invent the wheel to turn the command line arguments into that thing you need; you can specify "i want this or that" and get going from there. See here for some libraries around this topic.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248