3

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"?

2 Answers 2

8

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you expect some arguments to be passed on the command line, you can make things a little more robust and check that they are indeed passed. Then, pass the args array or its values to a constructor. Something like this:

public class App {
    private final String arg0;
    private final String arg1;

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("arguments must be supplied");
            System.out.println("Usage: java App <arg0> <arg1>");
            System.exit(1);
        }
        // optionally, check that there are exactly 2 arguments
        if (args.length > 2) {
            System.out.println("too many arguments");
            System.out.println("Usage: java App <arg0> <arg1>");
            System.exit(1);
        }

        new App(args[0], args[1]).echo();
    }

    public App(String arg0, String arg1) {
        this.arg0 = arg0;
        this.arg1 = arg1;
    }

    public void echo() {
        System.out.println(arg0);
        System.out.println(arg1);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.