Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java passing command line arguments to methods

I'm writing a program, which takes two words as command line arguments, does something to them, and prints out the result. I'm writing a class to handle this, and my question is: what is the best way to pass two words given as command line arguments between methods in a class? Why can't I use the usual "this.variable = " in the constructor with "args"?

like image 918
rize Avatar asked Nov 24 '25 08:11

rize


1 Answers

You can, if you pass args to the constructor:

public class Program
{
    private String foo;
    private String bar;

    public static void main(String[] args) 
    {
        Program program = new Program(args);
        program.run();
    }

    private Program(String[] args)
    {
        this.foo = args[0];
        this.bar = args[1];
        // etc
    }

    private void run()
    {
        // whatever
    }
}
like image 57
Jon Skeet Avatar answered Nov 26 '25 22:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!