Main method with int, Object, and String arguments []

advertisements

I got the below code from internet and even though there are 3 main methods, if I run the app from command prompt:

java MainTest 1 2 3

I would get the output:

String main 1

public class MainTest {

    public static void main(int [] args) {
        System.out.println("int main " + args[0]);
    }
    public static void main(Object[] args) {
        System.out.println("Object main " + args[0]);
    }

    public static void main(String[] args) {
        System.out.println("String main " + args[0]);
    }

}

  • Is there any scenario where more than 1 main method is needed in the same class?

  • I have not used yet the main method with int, Object [] args? Is that even possible? I thought it was only possible with String[] args.

  • I was expecting getting an error message at runtime. Why I did not get any error when the application ran? Does it mean that the parameters passed are always parsed to String and Java gets the main method that suits best?


Thanks a lot!!


The example shows overloading

main method is overloaded.

JVM only looks for main method which is static and it should accept only one argument of String array. So you are getting String main as output

Is there any scenario where more than 1 main method is needed in the same class?

It only depends on your requirement

I have not used yet the main method with int, Object [] args? is that even possible? I thought it was only possible with String[] args

I think you want to call the main method with Object[] argument. public static void main(Object[] args) { is like any other simple method and you can call it by MainTest.main(new Object{1,2})

I was expecting getting an error message at runtime. Why I did not get any error when the application ran? Does it mean that the parameters passed are always parsed to String and Java gets the main method

The code is perfectly fine and so you are not getting any error.The code describes an example of overloading of main method