0

I have a Java program in which I need to accept the command line arguments in an array as input in the main method, and then need to pass the array to a constructor of another class in the same program. I need to know how to declare the array globally and then how to pass it and take it in the constructor.

Thanks

2
  • Why do you think you need to declare the array globally (in java its public) to pass it in any constructor? Since you will be invoking the constructor from the main method itself, you can pass the array that you get as commandline argument, to the constructor. Commented Oct 19, 2012 at 18:17
  • 2
    Don't consider using global variables. As to passing information into a constructor, you give the accepting class's constructor a parameter that will accept the data, and you pass it in when calling this constructor. Commented Oct 19, 2012 at 18:17

3 Answers 3

1
public class Example{

  Example(String s[])
  { 
   AnotherClass ac = new AnotherClass(s);
  }
  public static void main(String[] args){
  int num=args.length;
  String s[]=new String[num]; 
  Example ex = new Example (s);`
  }
}

And you can create AnotherClass

public class AnotherClass{
  AnotherClass(String s[])
  { 
   // array argument constructor
  }
}

You can run using

javac Example.java

java Example

Sign up to request clarification or add additional context in comments.

1 Comment

I cannot call the AnotherClass from the Main() method but I need to call it from the constructor of Example class and I have 2 arrays. So Do you first want me to pass the 2 arrays from the main() method to the constructor of the Example class and then from the constructor call the AnotherClass with the arrays? If possible, can you please show me the way to do it
0
class SomeOtherClass{
   public SomeOtherClass(String[] args){
       this.arguments = args;
   }
   private String[] arguments;
}
class YourMainClass{

 public static void main(String[] args){
     SomeOtherClass cl = new SomeOtherClass(args);
    //fanny's your aunt
  }
}

This is how you can pass the arguments to SomeOtherClass's constructor.

Comments

0

In your class that contains the main method, you could have a class variable like:

String[] cmdLineArgs;

then in the main method:

cmdLineArgs = new String[args.length];
this.cmdLineArgs = args;

and then just implement a getter that will return cmdLineArgs. Then to call another constructor:

YourObject x = new YourObject(yourFirstClass.getCmdLineArgs());

(you don't need all those steps if you're calling this other constructor from the main method of course, you can just call the constructor with args directly)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.