简体   繁体   中英

Java - public static void main()

Should there be any specific order in which I should write the following for a Java main method?

public static void main()

In other words, can I re-shuffle public, static, void in any order?

Why or why not?

void is the return type, so it must go last. The others can be shuffled (see section 8.4 of the Java Language Specification for more details on this), but by convention the access modifier usually goes before most of the other method modifiers, except for annotations which usually go first (again, just by convention).

We can write, we can interchange static and public

static public void main(String args[])

static public void main(String... args)

However you cannot reshuffle the return type with any position, for eg

public void static main(String[] args) // is wrong

and also

static void public main(String[] args) // is also wrong

In short, NO, you cant The method name should be immediately prefixed with the return type of the method.Thats part of the method signature. Having the access specifier first is convention though.

The signature for main needs to be:

public static void main(String[] args){
    // Insert code here
}

However, there is no requirement that one method be placed before another method. They can be in whatever order you like. Additionally, Java uses a two-pass mechanism so that even if you use some other method in your "main" method, that method can actually appear later in the file. There is no requirement for forward declaration as in C and C++ because of this multi-pass approach taken by Java.

The modifiers public and static can be shuffled; however, by convention, the access modifier (public, private, protected) is always given first, static and/or final (if applicable) are given next, followed by the return-type.

You could have easily tried out the various permutations to see what does and does not work. For one thing, none of them will work if you don't change main() to main(String[] args) . Beyond that, public and static are modifiers that can come in any order, but most code style conventions have a prescribed order for them anyway. The void must be directly before the method name, since it's the return type, and not a modifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM