Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

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?

Upvotes: 9

Views: 42606

Answers (5)

JavaTechnical
JavaTechnical

Reputation: 9347

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

Upvotes: 6

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143104

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

Upvotes: 21

Zak
Zak

Reputation: 7078

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.

Upvotes: 1

Steve
Steve

Reputation: 1631

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.

Upvotes: 1

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95489

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.

Upvotes: 1

Related Questions