开发者

Java - public static void main()

Shoul开发者_如何学Cd 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 e.g.

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

and also

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜