The String[] you receive in the main method is a special case; it is populated with the arguments entered on the command line when starting java. Typically this data is processed immediately and influences how the program runs. If you want to access this array in other classes, you have options:
create an instance of the other class, and pass the array as an argument:
public static void main(String[] args) {
OtherClass other = new OtherClass(args);
create an instance of the main class, set the array as a field and add a getter:
public class MyApp {
private String[] args;
public static void main(String[] args) {
MyApp myApp = new MyApp();
myApp.setArgs(args);
OtherClass other = new OtherClass(myApp);
}
public String[] getArgs() { return args;}
public void setArgs(String[]) { this.args = args;}
...
public class OtherClass {
public OtherClass(MyApp myApp) {
String[] args = myApp.getArgs();
It all boils down to the same thing: You have to pass or receive the reference via a constructor or method call.
EDIT: If you are worried about the contents of the array being changed, you could for example create a List<String>
with the contents of the array. Lists are more flexible to use than arrays, so that's usually what you want anyway:
public static void main(String[] args) {
OtherClass other = new OtherClass(new ArrayList<>(Arrays.asList(args)););
...
public class OtherClass {
private final List<String> data;
public OtherClass(List<String> data) {
this.data = data;
}