Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call the main method passing args[] from another method?

Tags:

I'm trying to call the main method of a class from another method passing arguments like when running the class from the command line. Is there a way to do this?

like image 554
abcdefg Avatar asked Nov 08 '10 09:11

abcdefg


People also ask

Can we call main method in another method?

Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.

Why do we use args [] in the main method?

When you run Java program, by right click on Java class with main method, it creates a Run Argument for that class. By the way, you can write your String args[] as String[] args as well, because both are valid way to declare String array in Java.

Can we pass arguments to the main method?

Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.

Can I call a method from another method in Java?

We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.


1 Answers

You can call the main method as you would call any other (static) method:

MyClass.main(new String[] {"arg1", "arg2", "arg3"});

Example:

class MyClass {
    public static void test() {
        MyClass.main(new String[] {"arg1", "arg2", "arg3"});
    }

    public static void main(String args[]) {
        for (String s : args)
            System.out.println(s);
    }
}
like image 114
Grodriguez Avatar answered Dec 03 '22 03:12

Grodriguez