Tren46
Tren46

Reputation: 193

Does it matter where you put the brackets in the main method?

I am currently starting to learn Java and I have been looking at some code and have seen the brackets in two different places.

These are the two ways I have seen it:

public static void main(String[] args) {

public static void main(String args[]) {

Is one of these ways correct formatting or is it simply whichever the programmer prefers?

Upvotes: 6

Views: 3884

Answers (4)

Andy Turner
Andy Turner

Reputation: 140319

From the Google Java style guide:

The square brackets form a part of the type, not the variable: String[] args, not String args[].

However, both are legal.

Upvotes: 3

Tobias Brösamle
Tobias Brösamle

Reputation: 598

It's a matter of taste, you can write String[] args or String args[]. However, please be consistent, i.e. choose one of them and use this method for every array declaration as it improves readability.

I personally always write String[] args as in my opinion, you should see by the type that it is an array. Also, it is more consistent with String[] array = new String[count], since the brackets go with the type on the right hand side.

Upvotes: 0

sisyphus
sisyphus

Reputation: 6392

From the JLS:

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.

It makes no difference. The two forms exist so as not to scare off C/C++ programmers from learning Java.

Upvotes: 1

Zircon
Zircon

Reputation: 4707

Technically, it is a matter of your preference. When defining arrays, both are legal.

However, there is an overwhelming tendency and standard to put the brackets after the reference type, as in String[] args. Some code inspection tools even consider the other use of brackets as a bad convention or "code smell".

Upvotes: 11

Related Questions