4

This is a total beginners question. I am new to java and have been browsing StackOverflow and CodeReview. I am finding these two different formats being used:

example 1:

public static void main(String args[])

or
example 2:

public static void main(String[] args)

This is what I have in my course notes:

These words are called modifiers. The main() method is also preceded by the word void to indicate that it does not return any value. Also the main() method always has a list of command line arguments that can be passed to the program

main(String[] args)

which we are going to ignore for now.

So, as you can see, we have been told to ignore this for now, but I'd like to know:

Is there an actual difference between these, if so, what?

Community
  • 1
  • 1

4 Answers4

8

From the Java Language Specification:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

For example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];
Community
  • 1
  • 1
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
4

Actaully there are no difference between two main-method defination and both are correct.

But by convention java prefers array declaration as String[] args rather than String args[].

So it is more conventional -

public static void main(String[] args){...}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
4

main method accepts arguement in String array following ways are accepted

public static void main(String args[])
public static void main(String []args)
public static void main(String... args)
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
1

All these are valid declarations of the main function in Java.

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

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

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

public static void main(String[] MarkElliotZuckerberg) {
    // code
}

public static void main(String... NewYork) {
    // code
}
  • The keywords public and static are interchangeable but mandatory.
  • The parameter of the main method can take the var-args syntax.
  • The name can be anything..!

These are examples of invalid main method declarations -

static void main(String[] args) {
    // public is missing
}

public void main(String args[]) {
    // static is missing
}

public static int main(String... Java) {
    // return type not void

    return 0;
}

public void Main(String args[]) {
    // "main" not "Main"
}

public void main(string args[]) {
    // "String" not "string"
}

public void main(String.. SayHi) {
    // Ellipses is 3 dots !
}

I'm sorry if the source code is not soo readable... I always had trouble posting source code... :P ... Hope this helps...! If it did, let me know by commenting..!

Source - Java Tutorials on Theory of Programming

Vamsi Sangam
  • 948
  • 1
  • 11
  • 16