4

i was wondering whats the difference between these two

String values[] = new String[10]

String[] values = new String[10]

Both of these are used the same way. We can manipulate data in them the same way so whats the difference.

The Java tutorial uses the latter one for declaring arrays. Which one should we use ?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Sheraz Ahmad Khilji
  • 8,300
  • 9
  • 52
  • 84

6 Answers6

1

both are same .these are just different forms of array declaration Following are the different ways of array declarations

    String[] x = new String[3];
    String[] x = {"a","b","c"};
    String[] x = new String[]{"a","b","c"};

    String x[] = new String[3];
    String x[] = {"a","b","c"};
    String x[] = new String[]{"a","b","c"};

In all the cases x.length will output 3

Tiny
  • 27,221
  • 105
  • 339
  • 599
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
1

According to 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.

So yes they are the same. For example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];
Jatin
  • 31,116
  • 15
  • 98
  • 163
0

Really only a matter of personal preference. I Prefer String[], as it makes clear that the [] belongs to the type of the variable. But I guess reasons for using the old syntax can be found, too.

Johannes H.
  • 5,875
  • 1
  • 20
  • 40
0

They're equivalent.

The first one is more c style syntax, so they kept it in java.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
0

Both are valid syntax, and result in the exact same bytecode. Oracle's (and formally Sun's) convention is to use the latter form (String[] values = new String[10]), as would almost any open source project you encounter - i.e., this is the one you should use.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

According to JLS on Arrays

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.

Jainendra
  • 24,713
  • 30
  • 122
  • 169