public static void main(String arg[ ] ) in java is it fixed?

前端 未结 9 1315
离开以前
离开以前 2020-12-03 03:25

I was recently asked in an exam if public static void main(String arg[]) format of main method was fixed? Can we change it? Can we use main

相关标签:
9条回答
  • 2020-12-03 04:16

    The main method must be public so it can be found by the JVM when the class is loaded. Similarly, it must be static so that it can be called after loading the class, without having to create an instance of it. All methods must have a return type, which in this case is void.

    0 讨论(0)
  • 2020-12-03 04:21
                 Public static void main(String [] ar)
    

    To understand this we need to know the syntax of method and the array.

    Syntax of method is :

    return type methodName

    so the main method is written along with void which is return type.

    Syntax of Array:

    datatype [] arrayName

    the square braces indicates whether it is the of dimension array .Since we have one pair of square braces it is one dimension array.

    The meaning of words in the main method:

    Public: Public is the access specifier it is intended for the purpose of the JVM to execute the main method from any location.

    Static : Static is a modifier.The main method must be declared as static so that the JVM can access the main method directly by using the class name.

    When we execute a java program we use the class name so when we write static it will help the JVM to access the main method.

    If we remove static then it becomes instance method,to access an instance method we should create and object and then invoke the method using the object reference.

    void : Void is the return type of main method. The Caller of the main method is JVM and the JVM does not expect any value from the main method and there fore the main method should not return any value.This is the reason for specifying Void.

    main : Main is the method name and it is fixed as per the Java coding conventions.

    String[]: It is used for storing the command line arguments.The name of the array can be any valid Java identifier.

    So after String[] we can give name as any valid java identifier it can be 'ar' or it can be 'args'.

    0 讨论(0)
  • 2020-12-03 04:24

    You can change it if you create a new loader for your app. The public static void main( String args[] ) format is just the default solution people working on the JVM found to call your Java programs, so that there is a definite way to do it.

    The real implementation we have today just uses the JNI interface to call the public static void main (String args[]) method by using this function, so you could easily write exactly the same code if you wanted using JNI and have a different method to load your app.

    Here's an example in code that was taken from this page.

    Here's the current linux launcher program, the method lookup starts here.

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