Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - public static void main()

Tags:

java

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?

like image 699
Saurabh Gokhale Avatar asked Mar 21 '10 06:03

Saurabh Gokhale


5 Answers

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).

like image 159
Laurence Gonsalves Avatar answered Nov 06 '22 21:11

Laurence Gonsalves


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
like image 34
JavaTechnical Avatar answered Nov 06 '22 21:11

JavaTechnical


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.

like image 42
Michael Aaron Safyan Avatar answered Nov 06 '22 20:11

Michael Aaron Safyan


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.

like image 1
Steve Avatar answered Nov 06 '22 20:11

Steve


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.

like image 1
Zaki Avatar answered Nov 06 '22 20:11

Zaki