Two Main methods with different signatures

后端 未结 10 1441
旧时难觅i
旧时难觅i 2021-01-18 17:53

I have following class.

public class Test {

    public static void main(Integer[] args) {
        System.out.println(\"This is not a main\"); 
    }   

           


        
相关标签:
10条回答
  • 2021-01-18 17:57

    Because that's what Java always looks for. Java Language Specification, Section 12.1.4:

    The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String

    0 讨论(0)
  • 2021-01-18 17:57

    Because Strings are what you're passing into the command line.

    the 45 from

    myProgram.exe 45

    is not an integer. it is a string containing the characters 4 and 5

    It just so happens that you can use a string like "45" to represent an integer. It's a little more difficult to do it the other way around.(for the user at least)

    0 讨论(0)
  • 2021-01-18 17:58

    Aside from what others have mentioned, you can use var-args to implement String array.

    public static void main (String ...a)
    
    0 讨论(0)
  • 2021-01-18 17:58

    The signature of the main method in java is public static void main(String[] args) {} and that is what the JVM's classloader loads at the start of the program. The other main with an Integer argument won't be called unless you did it manually inside main. Try modifying your code as shown below and you'll notice that nothing will be called and your program won't print anything.

    public class Test {
       public static void main(Integer[] args) {
          System.out.println("This is not a real main so nothing gets printed"); 
      }   
    }
    

    Btw, you can write an overloaded main method with any argument that you want. As long as the argument is not String[] or String... which are the same, nothing will start rolling the program.

    0 讨论(0)
  • 2021-01-18 18:03

    For further information check this doc

    http://docs.oracle.com/javase/tutorial/getStarted/application/

    And also

    Using int Instead Of String: public static void main (int[] args)

    0 讨论(0)
  • 2021-01-18 18:05

    We always enter command line args as Strings. :)

    0 讨论(0)
提交回复
热议问题